Commit c3b104dd authored by Frank Elsinga's avatar Frank Elsinga Committed by Yovoslav Yovchev
Browse files

feat: add cost fn support

parent 5b748021
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
@@ -51,6 +51,9 @@ pub struct Function {

    /// Whether or not this function is `async` or not
    r#async: bool,

    /// Whether or not this function is `const` or not
    r#const: bool,
}

impl Function {
@@ -70,6 +73,7 @@ impl Function {
            attributes: vec![],
            extern_abi: None,
            r#async: false,
            r#const: false,
        }
    }

@@ -97,6 +101,12 @@ impl Function {
        self
    }

    /// Set whether this function is const or not
    pub fn set_const(&mut self, r#const: bool) -> &mut Self {
        self.r#const = r#const;
        self
    }

    /// Add a generic to the function.
    pub fn generic(&mut self, name: impl Into<String>) -> &mut Self {
        self.generics.push(name.into());
@@ -229,6 +239,10 @@ impl Function {
                self.vis.is_none(),
                "trait fns do not have visibility modifiers"
            );
            assert!(
                !self.r#const,
                "functions in traits cannot be declared const"
            );
        }

        if let Some(ref vis) = self.vis {
@@ -239,9 +253,16 @@ impl Function {
            write!(fmt, "extern \"{extern_abi}\" ", extern_abi = extern_abi)?;
        }

        assert!(
            !(self.r#async && self.r#const),
            "fns cannot be both `const` and `async`"
        );
        if self.r#async {
            write!(fmt, "async ")?;
        }
        if self.r#const {
            write!(fmt, "const ")?;
        }

        write!(fmt, "fn {}", self.name)?;
        fmt_generics(&self.generics, fmt)?;
+18 −0
Original line number Diff line number Diff line
@@ -578,6 +578,24 @@ trait Foo {
    assert_eq!(scope.to_string(), &expect[1..]);
}

#[test]
fn function_with_const() {
    let mut scope = Scope::new();

    scope
        .new_fn("one_plus_one")
        .set_const(true)
        .ret("u32")
        .line("1 + 1");

    let expect = r#"
const fn one_plus_one() -> u32 {
    1 + 1
}"#;

    assert_eq!(scope.to_string(), &expect[1..]);
}

#[test]
fn trait_with_macros() {
    let mut scope = Scope::new();