Search code examples
rustcode-generation

Generate func by codegen


I wanna write a func generator by codegen

use codegen::{Scope, Function};

fn main() {
    let mut scope = Scope::new();

    let add_function = Function::new("add")
        .arg("a", "i32")
        .arg("b", "i32")
        .ret("i32")
        .line("return a+b;")
        .doc("s");
    println!("{:?}", add_function.to_string());
}

but i got error:

 note: the following trait bounds were not satisfied:
           `&mut Function: std::fmt::Display`
           which is required by `&mut Function: ToString`
           `Function: std::fmt::Display`
           which is required by `Function: ToString`

i wanna save code of generated function and save it somewhere as a text


Solution

  • You need to call Scope::push_fn() with your Function and then call to_string() on the scope:

    use codegen::{Scope, Function};
    
    fn main() {
        let mut scope = Scope::new();
    
        let mut add_function = Function::new("add");
        add_function
            .arg("a", "i32")
            .arg("b", "i32")
            .ret("i32")
            .line("return a+b;")
            .doc("s");
        scope.push_fn(add_function);
        println!("{:?}", scope.to_string());
    }