Upsilon/Upsilon/Evaluator/EvaluationScope.cs

71 lines
1.9 KiB
C#

using System.Collections.Generic;
using Upsilon.BaseTypes;
using Upsilon.Binder;
namespace Upsilon.Evaluator
{
internal class EvaluationScope
{
private readonly EvaluationScope _parentScope;
private readonly Dictionary<VariableSymbol, LuaType> _variables;
internal EvaluationScope(EvaluationScope parentScope)
{
_parentScope = parentScope;
_variables = new Dictionary<VariableSymbol, LuaType>();
}
internal EvaluationScope(Dictionary<VariableSymbol, LuaType> vars)
{
_variables = vars;
}
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)
{
if (_parentScope != null)
_parentScope.SetGlobal(symbol, obj);
else
{
Set(symbol, obj);
}
}
public bool TryGet(VariableSymbol symbol, out LuaType obj)
{
if (_variables.TryGetValue(symbol, out obj))
return true;
if (_parentScope != null)
if (_parentScope.TryGet(symbol, out obj))
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;
};
}
if (_parentScope != null)
if (_parentScope.TryGet(variable, out obj))
return true;
obj = null;
return false;
}
}
}