From 780d4d03b57abea093b578b85bc6886fe1512468 Mon Sep 17 00:00:00 2001 From: DemonExposer Date: Tue, 19 Jul 2022 16:49:37 +0200 Subject: [PATCH] Return statements are now not allowed outside of functions (mostly) --- Tokens/Operators/N-Ary/MultilineStatementOperator.cs | 11 +++++++++-- Types/Function/FunctionBody.cs | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Tokens/Operators/N-Ary/MultilineStatementOperator.cs b/Tokens/Operators/N-Ary/MultilineStatementOperator.cs index 8e8095e..5e96ca0 100644 --- a/Tokens/Operators/N-Ary/MultilineStatementOperator.cs +++ b/Tokens/Operators/N-Ary/MultilineStatementOperator.cs @@ -6,16 +6,23 @@ namespace Interpreter.Tokens.Operators.N_Ary; public class MultilineStatementOperator : NAryOperator { + public bool IsPartOfFunction = false; + public MultilineStatementOperator() { Symbol = "{}"; } public override Object Evaluate(List> vars) { foreach (Token t in Children) { - if (t is ReturnStatement) // TODO: add flag to check if this is part of a function + if (t is ReturnStatement) { + if (!IsPartOfFunction) + throw new FormatException("Line " + t.Line + ": return statement not allowed outside of function"); + return t.Evaluate(vars); + } - if (t is BinaryStatement) { + if (t is BinaryStatement bs) { + ((MultilineStatementOperator) bs.Right).IsPartOfFunction = IsPartOfFunction; Object obj = t.Evaluate(vars); if (obj != null!) return obj; diff --git a/Types/Function/FunctionBody.cs b/Types/Function/FunctionBody.cs index 6cf564b..b5812ef 100644 --- a/Types/Function/FunctionBody.cs +++ b/Types/Function/FunctionBody.cs @@ -4,10 +4,12 @@ namespace Interpreter.Types.Function; public class FunctionBody { - public MultilineStatementOperator expressions; + public MultilineStatementOperator expressions = null!; public FunctionBody(MultilineStatementOperator expressions) { this.expressions = expressions; + if (this.expressions != null!) + this.expressions.IsPartOfFunction = true; } public virtual Object Execute(Object[] args, TrieDictionary vars, List> topScopeVars) => expressions.Evaluate(new List> {topScopeVars[0], vars});