Upsilon/Upsilon/BaseTypes/ScriptTable.cs

76 lines
2.2 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2018-11-17 18:13:05 +00:00
using System.Linq;
2018-11-24 14:11:33 +00:00
using Upsilon.BaseTypes.Number;
2018-11-23 17:18:07 +00:00
using Upsilon.BaseTypes.ScriptTypeInterfaces;
2018-11-19 15:22:13 +00:00
using Upsilon.Binder;
2018-11-19 11:17:21 +00:00
using Upsilon.Evaluator;
using Upsilon.Text;
2018-11-17 18:13:05 +00:00
namespace Upsilon.BaseTypes
{
2018-11-24 14:11:33 +00:00
internal class ScriptTable : ScriptType, IIndexable, IScopeOwner, IIterable, ILengthType
2018-11-17 18:13:05 +00:00
{
2018-11-19 11:17:21 +00:00
public EvaluationScope EvaluationScope { get; }
2018-11-17 18:13:05 +00:00
2018-11-23 17:18:07 +00:00
public ScriptTable(EvaluationScope scope)
2018-11-17 18:13:05 +00:00
{
2018-11-19 11:17:21 +00:00
EvaluationScope = scope;
2018-11-17 18:13:05 +00:00
}
public override Type Type => Type.Table;
public override object ToCSharpObject()
{
2018-11-19 11:49:48 +00:00
return EvaluationScope.Variables.ToDictionary(x => x.Key, x => x.Value.ToCSharpObject());
2018-11-17 18:13:05 +00:00
}
public override System.Type GetCSharpType()
{
return typeof(Dictionary<string, object>);
}
2018-11-23 17:18:07 +00:00
public ScriptType Get(Diagnostics diagnostics, TextSpan span, ScriptType index, EvaluationScope scope)
2018-11-18 13:18:24 +00:00
{
var s = index.ToString();
2018-11-19 11:49:48 +00:00
if (EvaluationScope.TryGet(s, out var o))
2018-11-19 11:17:21 +00:00
{
return o;
}
diagnostics.LogError("Cannot find member 's' on Table", span);
2018-11-23 17:18:07 +00:00
return new ScriptNull();
2018-11-18 13:18:24 +00:00
}
2018-11-19 15:22:13 +00:00
2018-11-23 17:18:07 +00:00
public void Set(Diagnostics diagnostics, TextSpan span, ScriptType index, ScriptType value)
2018-11-19 15:22:13 +00:00
{
var s = index.ToString();
2018-11-24 11:42:54 +00:00
EvaluationScope.CreateLocal(new VariableSymbol(s, value.Type, false), value);
2018-11-19 15:22:13 +00:00
}
public ScriptType GetValueFromIndex(ScriptType index)
{
if (EvaluationScope.TryGet(index.ToString(), out var result))
{
return result;
}
throw new Exception($"Can't find key '{index}' in table.");
}
public IEnumerator<ScriptType> GetEnumerator()
{
2018-11-23 17:18:07 +00:00
return Enumerator();
}
private IEnumerator<ScriptType> Enumerator()
{
2018-11-23 17:18:07 +00:00
foreach (var variable in EvaluationScope.Variables)
{
yield return variable.Key.ToScriptType();
2018-11-23 17:18:07 +00:00
}
}
2018-11-24 14:11:33 +00:00
public ScriptNumberLong Length()
{
return new ScriptNumberLong(EvaluationScope.Variables.Count);
}
2018-11-17 18:13:05 +00:00
}
}