Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow more constant types #6

Merged
merged 2 commits into from
Jul 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions GrobExp.Compiler.Tests/TestCompileToMethod.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

using NUnit.Framework;

namespace GrobExp.Compiler.Tests
{
[TestFixture]
public class TestCompileToMethod
{
[OneTimeSetUp]
public void SetUp()
{
var assemblyName = "TestAssembly";
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.Run);
moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName);
}

[Test]
public void TestNullablePrimitiveConstant()
{
var typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString(), TypeAttributes.Class);
var methodName = nameof(TestNullablePrimitiveConstant);
var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static);

// Cannot declare constant of nullable type via Expression<Func<>> interface
// Expression<Func<int?, string>> expression = x => x == (int? 2) ? "two" : x.ToString();
var parameter = Expression.Parameter(typeof(int?));
var constant = Expression.Constant((int?)2, typeof(int?));
var condition = Expression.Condition(Expression.Equal(parameter, constant),
Expression.Constant("two", typeof(string)),
Expression.Call(parameter, typeof(int?).GetMethod("ToString", Type.EmptyTypes)));
var lambda = Expression.Lambda(condition, parameter);

LambdaCompiler.CompileToMethod(lambda, methodBuilder, CompilerOptions.All);

var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, new[] {typeof(int?)});
Assert.That(method.Invoke(null, new object[] {new int?(2)}), Is.EqualTo("two"));
Assert.That(method.Invoke(null, new object[] {new int?(3)}), Is.EqualTo("3"));
}

[Test]
public void TestEnumConstant()
{
var typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString(), TypeAttributes.Class);
var methodName = nameof(TestEnumConstant);
var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static);

// Cannot use Expression<Func<>> interface here because enum type gets optimized to int
// Expression<Func<TestEnum, string>> expression = x => x == TestEnum.Two ? "2" : x.ToString();
var parameter = Expression.Parameter(typeof(TestEnum));
var constant = Expression.Constant(TestEnum.Two, typeof(TestEnum));
var condition = Expression.Condition(Expression.Equal(parameter, constant),
Expression.Constant("2", typeof(string)),
Expression.Call(parameter, typeof(object).GetMethod("ToString", Type.EmptyTypes)));
var lambda = Expression.Lambda(condition, parameter);

LambdaCompiler.CompileToMethod(lambda, methodBuilder, CompilerOptions.All);

var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, new[] {typeof(TestEnum)});
Assert.That(method.Invoke(null, new object[] {TestEnum.Two}), Is.EqualTo("2"));
Assert.That(method.Invoke(null, new object[] {TestEnum.One}), Is.EqualTo("One"));
}

[Test]
public void TestDecimalConstant()
{
var typeBuilder = moduleBuilder.DefineType(Guid.NewGuid().ToString(), TypeAttributes.Class);
var methodName = nameof(TestDecimalConstant);
var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.Static);

Expression<Func<decimal, string>> expression = x => x == 2m ? "two" : x.ToString();
LambdaCompiler.CompileToMethod(expression, methodBuilder, CompilerOptions.All);

var type = typeBuilder.CreateType();
var method = type.GetMethod(methodName, new[] {typeof(decimal)});
Assert.That(method.Invoke(null, new object[] {2m}), Is.EqualTo("two"));
Assert.That(method.Invoke(null, new object[] {3m}), Is.EqualTo("3"));
}

public enum TestEnum
{
One,
Two,
}

private ModuleBuilder moduleBuilder;
}
}
9 changes: 8 additions & 1 deletion GrobExp.Compiler/Closures/ExpressionClosureBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,13 +144,20 @@ protected override CatchBlock VisitCatchBlock(CatchBlock node)

protected override Expression VisitConstant(ConstantExpression node)
{
if(quoteDepth > 0 || node.Value == null || node.Type.IsPrimitive || node.Type == typeof(string))
if(quoteDepth > 0 || node.Value == null || IsPrimitiveConstantType(node.Type))
return node;
if(!constants.ContainsKey(node))
constants.Add(node, BuildConstField(node.Type, node.Value));
return node;
}

private static bool IsPrimitiveConstantType(Type type)
{
if (type.IsNullable())
type = type.GetGenericArguments()[0];
return type.IsPrimitive || type.IsEnum || type == typeof(string) || type == typeof(decimal);
}

protected override Expression VisitParameter(ParameterExpression node)
{
var peek = localParameters.Peek();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ protected override bool EmitInternal(ConstantExpression node, EmittingContext co
case TypeCode.String:
context.Il.Ldstr((string)node.Value);
break;
case TypeCode.Decimal:
context.Il.LdDec((decimal)node.Value);
break;
default:
throw new NotSupportedException("Constant of type '" + node.Type + "' is not supported");
}
Expand Down
2 changes: 1 addition & 1 deletion GrobExp.Compiler/GrobExp.Compiler.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@
<RepositoryType>git</RepositoryType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="GrEmit" Version="2.2.1" />
<PackageReference Include="GrEmit" Version="2.2.2" />
</ItemGroup>
</Project>