Upsilon/Upsilon/Evaluator/EvaluationScope.cs

72 lines
2.0 KiB
C#
Raw Normal View History

2018-11-14 15:39:52 +00:00
using System;
using System.Collections.Generic;
using Upsilon.BaseTypes;
using Upsilon.Binder;
namespace Upsilon.Evaluator
{
public class EvaluationScope
{
2018-11-15 19:13:53 +00:00
public readonly EvaluationScope ParentScope;
2018-11-14 15:39:52 +00:00
private readonly Dictionary<VariableSymbol, LuaType> _variables;
internal EvaluationScope(EvaluationScope parentScope)
{
2018-11-15 19:13:53 +00:00
ParentScope = parentScope;
2018-11-14 15:39:52 +00:00
_variables = new Dictionary<VariableSymbol, LuaType>();
}
internal EvaluationScope(Dictionary<VariableSymbol, LuaType> vars)
{
2018-11-15 19:13:53 +00:00
_variables = new Dictionary<VariableSymbol, LuaType>();
2018-11-14 15:39:52 +00:00
}
public void Set(VariableSymbol symbol, LuaType obj)
{
if (_variables.ContainsKey(symbol))
{
_variables[symbol] = obj;
}
else
{
_variables.Add(symbol, obj);
}
}
public void SetGlobal(VariableSymbol symbol, LuaType obj)
{
2018-11-15 19:13:53 +00:00
if (ParentScope != null)
ParentScope.SetGlobal(symbol, obj);
2018-11-14 15:39:52 +00:00
else
{
Set(symbol, obj);
}
}
public bool TryGet(VariableSymbol symbol, out LuaType obj)
{
if (_variables.TryGetValue(symbol, out obj))
return true;
2018-11-15 19:13:53 +00:00
if (ParentScope != null)
if (ParentScope.TryGet(symbol, out obj))
2018-11-14 15:39:52 +00:00
return true;
return false;
}
public bool TryGet(string variable, out LuaType obj)
{
foreach (var luaType in _variables)
{
if (luaType.Key.Name == variable)
{
obj = luaType.Value;
return true;
};
}
2018-11-15 19:13:53 +00:00
if (ParentScope != null)
if (ParentScope.TryGet(variable, out obj))
return true;
obj = null;
return false;
}
2018-11-14 15:39:52 +00:00
}
}