Upsilon/Upsilon/BoundTypes/UserDataBoundTypeDefinition.cs
2018-12-05 15:18:41 +01:00

101 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Upsilon.BaseTypes;
using Type = Upsilon.BaseTypes.Type;
namespace Upsilon.BoundTypes
{
public class UserDataBoundTypeDefinition : BoundTypeDefinition
{
public string Name { get; }
public Dictionary<string, UserDataBoundProperty> Properties { get; protected set; }
internal UserDataBoundTypeDefinition(System.Type backingType)
: base(Type.UserData, backingType)
{
Name = backingType.Name;
}
public static UserDataBoundTypeDefinition Create(System.Type backingType)
{
var obj = new UserDataBoundTypeDefinition(backingType)
{
Properties = new Dictionary<string, UserDataBoundProperty>()
};
var fields = backingType.GetFields().Select(x => new UserDataBoundProperty()
{
Name = x.Name,
ActualType = x.FieldType.Name,
Type = x.FieldType.GetScriptType(),
});
foreach (var f in fields)
{
obj.Properties.Add(f.Name.ToLowerInvariant(), f);
}
var properties = backingType.GetProperties().Select(x => new UserDataBoundProperty()
{
Name = x.Name,
ActualType = x.PropertyType.Name,
Type = x.PropertyType.GetScriptType(),
});
foreach (var f in properties)
{
obj.Properties.Add(f.Name.ToLowerInvariant(), f);
}
var methods = backingType.GetMethods().Select(x => new UserDataBoundMethod()
{
Name = x.Name,
Type = Type.Function,
ResultType = x.ReturnType.GetScriptType()
});
foreach (var f in methods)
{
obj.Properties.Add(f.Name.ToLowerInvariant(), f);
}
return obj;
}
}
public class UserDataBoundEnumDefinition : UserDataBoundTypeDefinition
{
public UserDataBoundEnumDefinition(System.Type enumType) : base(enumType)
{
if (!enumType.IsEnum)
throw new Exception("Trying to bind an enum with a type that's not an enum");
Properties = new Dictionary<string, UserDataBoundProperty>();
var enumUnderlyingType = Enum.GetUnderlyingType(enumType);
var enumValues = Enum.GetValues(enumType);
for (var i=0; i < enumValues.Length; i++)
{
var value = enumValues.GetValue(i);
var name = value.ToString().ToLowerInvariant();
Properties.Add(name, new UserDataBoundProperty()
{
Name = name,
ActualType = enumUnderlyingType.ToString(),
Type = Type.Number
});
}
}
}
public class UserDataBoundProperty
{
public string Name { get; set; }
public Type Type { get; set; }
public virtual string ActualType { get; set; }
public string Comment { get; set; }
}
public class UserDataBoundMethod: UserDataBoundProperty
{
public override string ActualType => "Function";
public Type ResultType { get; set; }
}
}