Problem with lifetime (with inkwell module)

Recently I was using inkwell to write a code generator with the help from LLVM.
I first parse my code into a Abstract Syntax Tree (AST), and I planned to walk through the tree to generate code.
Here is what I implemented:
I create a struct that warp Inkwell's context, builder, module inside. I have to add the explicit 'ctx lifetime because builder/module belong to context. This is limited by Inkwell library.

pub struct LLVMCodeGen<'ctx> {
  pub context : Context,
  pub builder : Builder<'ctx>,
  pub module  : Module<'ctx>
}

Later I can add a trait ToLLVM, which implement the function walk through the AST

trait ToLLVM {
    fn compile(&self, visit: &mut LLVMCodeGen);
}

and I can implement each struct in AST for this trait, and inside call LLVMCodeGen's function to generate code.
However, when I really call function in LLVMCodeGen, I got some lifetime error.

impl ToLLVM for FuncDef { //FuncDef is one of struct in AST
  fn compile(&self, visit: &mut LLVMCodeGen) {
    let fn_type = visiti.context.i32_type().fn_type(&[], false);
    visit.module.add_function("foo", fn_type, None);
  }
}

However, this will give me compile error related to lifetime, with mysterious message.

84 |     fn compile(&self, visit: &mut LLVMCodeGen) {
   |                              ----------------
   |                              |
   |                              these two types are declared with different lifetimes...
...
96 |         visit.module.add_function(&self.fun_name, fn_type, None);
   |                      ^^^^^^^^^^^^ ...but data from `visit` flows into `visit` here

I place the link to Inwell document below:
add_function

I am not quite sure what rustc want to told me. I only got ONE, not TWO, type, that is LLVMCodeGen in my code. and what does it means that data from visit flow into visit here.
I search the error message and I got some similar post or question, but none of them can solve the issue I faced.

You are trying to create a self-referential type, which is not possible. Consider reading this other thread, where we already discussed a very similar issue, and what other options you have.

@alice Thank you, I will read your thread well.
(I also play Touhou, nice to see another one who also like it)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.