From 005976e1ddf82b118076b17997de807b1df8f047 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Mon, 28 Dec 2020 23:54:12 +0100 Subject: [PATCH] Prevent self-referencing variables --- kalk/src/parser.rs | 4 ++++ kalk_cli/src/output.rs | 1 + 2 files changed, 5 insertions(+) diff --git a/kalk/src/parser.rs b/kalk/src/parser.rs index 026eb2d..c237f75 100644 --- a/kalk/src/parser.rs +++ b/kalk/src/parser.rs @@ -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 { 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))) } diff --git a/kalk_cli/src/output.rs b/kalk_cli/src/output.rs index 29bb93c..ced02fb 100644 --- a/kalk_cli/src/output.rs +++ b/kalk_cli/src/output.rs @@ -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) }