Create scoping for variables
Closed this issue · 1 comments
Techcraft7 commented
Implementation
Create a stack like structure called Scope
that has a Stack<Dictionary<string, object>>
When pushing a new scope, add all the contents of the current scope onto the stack so they are available
When popping a scope, set all of the values on the previous scope that exist on the scope to be popped to the value in the scope to be popped
Kind of C# for pushing/popping a scope:
public void PushScope() => stack.Push(stack.Peek());
public Dictionary<string, object> PopScope()
{
var ret = stack.Pop();
//get the previous scope
var modified = stack.Pop();
foreach (string key in modified.Keys)
{
if (!ret.ContainsKey(key))
{
continue;
}
modified[key] = ret[key];
}
//add the scope back to the stack
stack.Push(modified);
return ret;
}
Expressions to push scopes on start:
loop
if
while
function
Techcraft7 commented
Done!
Code to verify that this works
write("Outside");
a = 5;
write(a);
if (true) {
write("Inside");
x = 3;
write(a);
write(x);
}
write("Outside");
write(x);
Should output:
Outside
5
Inside
5
3
Outside
CodingSeb.ExpressionEvaluator.ExpressionEvaluatorSyntaxErrorException: Variable [x] unknown in expression : [x]
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.EvaluateVarOrFunc(String expression, Stack`1 stack, Int32& i)
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.<>c__DisplayClass237_1.<Evaluate>b__0(ParsingMethodDelegate parsingMethod)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.Evaluate(String expression)
at System.Collections.Generic.List`1.ConvertAll[TOutput](Converter`2 converter)
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.EvaluateVarOrFunc(String expression, Stack`1 stack, Int32& i)
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.<>c__DisplayClass237_1.<Evaluate>b__0(ParsingMethodDelegate parsingMethod)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at CodingSeb.ExpressionEvaluator.ExpressionEvaluator.Evaluate(String expression)
at _7Sharp.Intrerpreter.Interpreter.Evaluate(String expr) in C:\Users\Techcraft7\Source\7Sharp\7Sharp\Intrerpreter\Interpreter.cs:line 456
System.InvalidOperationException: Stack empty.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Stack`1.Pop()
at _7Sharp.Intrerpreter.Scope.PopScope() in C:\Users\Techcraft7\Source\7Sharp\7Sharp\Intrerpreter\Scope.cs:line 30
at _7Sharp.Intrerpreter.Interpreter.InternalRun(String code, Object& returnValue, Boolean reset, KeyValuePair`2[] passedParams) in C:\Users\Techcraft7\Source\7Sharp\7Sharp\Intrerpreter\Interpreter.cs:line 343
at _7Sharp.Intrerpreter.Interpreter.Run(String code) in C:\Users\Techcraft7\Source\7Sharp\7Sharp\Intrerpreter\Interpreter.cs:line 109