Prevent self-referencing variables

This commit is contained in:
PaddiM8 2020-12-28 23:54:12 +01:00
parent 865947dccd
commit e8c362c72e
2 changed files with 5 additions and 0 deletions

View File

@ -84,6 +84,7 @@ pub enum CalcError {
InvalidOperator,
InvalidUnit,
TimedOut,
VariableReferencesItself,
UnexpectedToken(TokenKind, TokenKind),
UndefinedFn(String),
UndefinedVar(String),
@ -195,6 +196,9 @@ fn parse_var_decl_stmt(context: &mut Context) -> Result<Stmt, CalcError> {
let identifier = advance(context).clone();
advance(context); // Equal sign
let expr = parse_expr(context)?;
if inverter::contains_var(&context.symbol_table, &expr, &identifier.value) {
return Err(CalcError::VariableReferencesItself);
}
Ok(Stmt::VarDecl(identifier.value, Box::new(expr)))
}

View File

@ -36,6 +36,7 @@ fn print_calc_err(err: CalcError) {
InvalidOperator => format!("Invalid operator."),
InvalidUnit => format!("Invalid unit."),
TimedOut => format!("Operation took too long."),
VariableReferencesItself => format!("Variable references itself."),
UnexpectedToken(got, expected) => {
format!("Unexpected token: '{:?}', expected '{:?}'.", got, expected)
}