I am new to Rust, I am having some problem with lifetime,
File github link
Code
fn visit_function(&mut self, expr: &Function) -> Result<Rc<Value>, ExprError> {
let name = &expr.name.lexeme;
let function = TullyCallable { declaration: expr };
self.globals
.define(name, Rc::new(Value::Function(Rc::new(function))));
Ok(Rc::clone(&self.constants.nil))
}
pub trait Callable {
fn arity(&self) -> usize;
fn call(
&self,
evaluator: &mut Evaluator,
arguments: Vec<Rc<Value>>,
) -> Result<Rc<Value>, ExprError>;
fn to_string(&self) -> String;
}
pub struct TullyCallable<'a> {
declaration: &'a Function<'a>,
}
impl<'a> Callable for TullyCallable<'a> {
fn arity(&self) -> usize {
self.declaration.params.len()
}
fn call(
&self,
evaluator: &mut Evaluator,
arguments: Vec<Rc<Value>>,
) -> Result<Rc<Value>, ExprError> {
evaluator.globals.new_env();
for (i, param) in self.declaration.params.iter().enumerate() {
evaluator
.globals
.define(¶m.lexeme, Rc::clone(&arguments[i]));
evaluator.execute_block(&self.declaration.body.statements, false)?;
}
evaluator.globals.delete_recent();
return Ok(Rc::clone(&evaluator.constants.nil));
}
fn to_string(&self) -> String {
format!("<fn {}>", self.declaration.name.lexeme)
}
}
#[derive(Clone)]
pub enum Value {
Boolean(bool),
Float(f64),
String(String),
Function(Rc<dyn Callable>),
Nil,
}
Error
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src/evaluator/evaluator.rs:334:24
|
334 | let function = TullyCallable { declaration: expr };
| ^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #3 defined on the method body at 332:5...
--> src/evaluator/evaluator.rs:332:5
|
332 | / fn visit_function(&mut self, expr: &Function) -> Result<Rc<Value>, ExprError> {
333 | | let name = &expr.name.lexeme;
334 | | let function = TullyCallable { declaration: expr };
335 | | self.globals
336 | | .define(name, Rc::new(Value::Function(Rc::new(function))));
337 | | Ok(Rc::clone(&self.constants.nil))
338 | | }
| |_____^
note: ...so that the expression is assignable
--> src/evaluator/evaluator.rs:334:53
|
334 | let function = TullyCallable { declaration: expr };
| ^^^^
= note: expected `&parser::expr::Function<'_>`
found `&parser::expr::Function<'_>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/evaluator/evaluator.rs:336:51
|
336 | .define(name, Rc::new(Value::Function(Rc::new(function))));
| ^^^^^^^^^^^^^^^^^
= note: expected `std::rc::Rc<(dyn evaluator::callable::Callable + 'static)>`
found `std::rc::Rc<dyn evaluator::callable::Callable>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0495`.
error: could not compile `tully`.
To learn more, run the command again with --verbose.
``