Upsilon/Upsilon/BaseTypes/ScriptString.cs

127 lines
3.5 KiB
C#

using System;
using Upsilon.BaseTypes.Number;
using Upsilon.BaseTypes.ScriptTypeInterfaces;
using Upsilon.Evaluator;
using Upsilon.Text;
namespace Upsilon.BaseTypes
{
internal class ScriptString : ScriptType, IIndexable, ILengthType
{
public ScriptString(string value)
{
Value = value;
}
public string Value { get; }
public override TypeContainer Type => BaseTypes.Type.String;
public override object ToCSharpObject()
{
return Value;
}
public override System.Type GetCSharpType()
{
return typeof(string);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is string str)
{
return string.Equals(str, Value);
}
if (!(obj is ScriptString s))
return false;
return Equals(s);
}
public override int GetHashCode()
{
return (Value != null ? Value.GetHashCode() : 0);
}
public static implicit operator string(ScriptString s)
{
return s.Value;
}
private bool Equals(ScriptString s)
{
return s != null && string.Equals(s.Value, Value);
}
public static ScriptString operator +(ScriptString a, ScriptType b)
{
switch (b)
{
case ScriptString s:
return a + s;
case ScriptBoolean bl:
return a + bl;
case ScriptNumberLong l:
return a + l;
case ScriptNumberDouble d:
return a + d;
}
throw new ArgumentException($"Adding Type '{b.Type}' to a LuaString is not supported.");
}
public static ScriptString operator +(ScriptString a, ScriptString b)
{
return new ScriptString(a.Value + b.Value);
}
public static ScriptString operator +(ScriptString a, ScriptBoolean b)
{
return new ScriptString(a.Value + b.Value);
}
public static ScriptString operator +(ScriptString a, ScriptNumberLong b)
{
return new ScriptString(a.Value + b.Value);
}
public static ScriptString operator +(ScriptString a, ScriptNumberDouble b)
{
return new ScriptString(a.Value + b.Value);
}
public override string ToString()
{
return Value;
}
public ScriptNumberLong Length()
{
return new ScriptNumberLong(Value.Length);
}
public ScriptType Get(Diagnostics diagnostics, TextSpan span, ScriptType index, EvaluationScope scope)
{
int i;
if (index.Type == BaseTypes.Type.String)
{
var str = (ScriptString)index;
i = int.Parse(str.Value);
}
else if (index.Type == BaseTypes.Type.Number)
{
var ind = (Number.ScriptNumberLong) index;
i = (int) ind.Value;
}
else
{
return null;
}
return new ScriptString(Value[i - 1].ToString());
}
public void Set(Diagnostics diagnostics, TextSpan span, ScriptType index, ScriptType value)
{
throw new NotSupportedException();
}
}
}