New() public static method

Creates a new NewExpression that represents calling the specified constructor that takes no arguments.
public static New ( ConstructorInfo constructor ) : NewExpression
constructor System.Reflection.ConstructorInfo The to set the property equal to.
return NewExpression
        private static Func <int[], int[]> GenerateCopyExpression()
        {
            var ctor = typeof(int[]).GetConstructor(new[] { typeof(int) });
            var get  = typeof(int[]).GetMethod("Get", new[] { typeof(int) });
            var set  = typeof(int[]).GetMethod("Set", new[] { typeof(int), typeof(int) });

            var p1     = Exp.Parameter(typeof(int[]));
            var v1     = Exp.Variable(typeof(int[]));
            var v2     = Exp.Variable(typeof(int));
            var @break = Exp.Label();

            var block = Exp.Block(
                new[] { v1, v2 },
                Exp.Assign(v1, Exp.New(ctor, Exp.Property(p1, "Length"))),
                Exp.Assign(v2, Exp.Constant(0)),
                Exp.Loop(
                    Exp.IfThenElse(
                        Exp.LessThan(v2, Exp.Property(p1, "Length")),
                        Exp.Block(
                            Exp.Call(v1, set, v2, Exp.Call(p1, get, v2)),
                            Exp.AddAssign(v2, Exp.Constant(1))
                            ),
                        Exp.Break(@break)
                        ),
                    @break),
                v1
                );

            return(Exp.Lambda <Func <int[], int[]> >(block, new ParameterExpression[] { p1 }).Compile());
        }
Beispiel #2
0
        private NewExpression NewExpression(
            ExpressionType nodeType, System.Type type, JObject obj)
        {
            var constructor = this.Prop(obj, "constructor", this.Constructor);
            var arguments   = this.Prop(obj, "arguments", this.Enumerable(this.Expression));
            var members     = this.Prop(obj, "members", this.Enumerable(this.Member));

            switch (nodeType)
            {
            case ExpressionType.New:
                if (arguments == null)
                {
                    if (members == null)
                    {
                        return(Expr.New(constructor));
                    }
                    return(Expr.New(constructor, new Expression[0], members));
                }
                if (members == null)
                {
                    return(Expr.New(constructor, arguments));
                }
                return(Expr.New(constructor, arguments, members));

            default:
                throw new NotSupportedException();
            }
        }
        private LambdaExpression toDictLambda(Type from, Type to)
        {
            var valueType = recordCreator.GetValueType(to);
            var recType   = typeof(IRecord <>).MakeGenericType(valueType);
            var set       = recType.GetTypeInfo().GetDeclaredMethod(nameof(IRecord <object> .SetValue));

            var input      = Ex.Parameter(from, "input");
            var tmp        = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(valueType), "tmp");
            var res        = Ex.Parameter(typeof(IDictionary <,>).MakeGenericType(typeof(string), valueType), "res");
            var rec        = Ex.Parameter(recType, "rec");
            var getters    = GetReadablePropertiesForType(from);
            var converters = getters.Select(g => Ref.GetLambda(g.PropertyType, valueType));

            var end   = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to));
            var block = Ex.Block(new[] { tmp, res, rec },
                                 Ex.Assign(res, Ex.New(GetParameterlessConstructor(to))),
                                 Ex.Assign(rec, recordCreator.Creator(to).ApplyTo(res)),
                                 Ex.IfThen(Ex.MakeBinary(ExpressionType.Equal, rec, Ex.Default(rec.Type)), Ex.Goto(end, NoResult(to))),
                                 Ex.Block(getters.Zip(converters, (g, c) => new { g, c })
                                          .Select(x =>
                                                  Ex.Block(
                                                      Ex.Assign(tmp, x.c.ApplyTo(Ex.Property(input, x.g))),
                                                      Ex.IfThenElse(Ex.Property(tmp, nameof(IConversionResult.IsSuccessful)),
                                                                    Ex.Call(rec, set, Ex.Constant(x.g.Name), Ex.Property(tmp, nameof(IConversionResult.Result))),
                                                                    Ex.Goto(end, NoResult(to)))))),
                                 Ex.Label(end, Result(to, Ex.Convert(res, to))));

            return(Ex.Lambda(block, input));
        }
Beispiel #4
0
        static GlyphRunFormatter()
        {
            var refType = typeof(CharacterBufferReference);

            _textFormattingMode = typeof(GlyphRun).GetField("_textFormattingMode", BindingFlags.NonPublic | BindingFlags.Instance);

            {
                var property = refType.GetProperty("CharacterBuffer", BindingFlags.NonPublic | BindingFlags.Instance);
                var param0   = Expr.Parameter(refType);
                var expr     = Expr.Convert(Expr.Property(param0, property), typeof(IList <char>));
                var lambda   = Expr.Lambda <Func <CharacterBufferReference, IList <char> > >(expr, param0);
                getCharBuf = lambda.Compile();
            }

            {
                var property = refType.GetProperty("OffsetToFirstChar", BindingFlags.NonPublic | BindingFlags.Instance);
                var param0   = Expr.Parameter(refType);
                var expr     = Expr.Property(param0, property);
                var lambda   = Expr.Lambda <Func <CharacterBufferReference, int> >(expr, param0);
                getCharOffset = lambda.Compile();
            }

            {
                var ctor   = typeof(TextBounds).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
                var param0 = Expr.Parameter(typeof(Rect));
                var expr   = Expr.New(ctor, param0, Expr.Constant(FlowDirection.LeftToRight), Expr.Constant(null, typeof(IList <TextRunBounds>)));
                var lambda = Expr.Lambda <Func <Rect, TextBounds> >(expr, param0);
                makeBounds = lambda.Compile();
            }
        }
Beispiel #5
0
        public EvaluationCallback Create(Node node)
        {
            var compilerstate = new CompilerState
            {
                FunctionState = Exp.Parameter(typeof(Character), "state"),
                ErrorVariable = Exp.Parameter(typeof(bool), "error")
            };
            var result = Make(compilerstate, node);

            if (result.Type == typeof(bool))
            {
                result = ToInteger(result);
            }
            if (result.Type == typeof(int) || result.Type == typeof(float))
            {
                // int or float convert to number
                var constructor = typeof(Number).GetConstructor(new[] { result.Type });
                result = Exp.New(constructor, new[] { result });

                // wrap the evaluation in a try..catch
                var exceptionParameter = Exp.Parameter(typeof(Exception), "e");
                var writeLineMethod    = typeof(Console).GetMethod(nameof(Console.WriteLine), new Type[] { typeof(string) });
                var toStringMethod     = typeof(Exception).GetMethod(nameof(Exception.ToString));
                var catchBody          = Exp.Block(
                    Exp.Call(null, writeLineMethod, Exp.Call(exceptionParameter, toStringMethod)),
                    Exp.Constant(new Number(0)));
                result = Exp.TryCatch(result, Exp.Catch(exceptionParameter, catchBody));
                // create lambda
                var func = Exp.Lambda <Func <Character, bool, Number> >(result, compilerstate.FunctionState, compilerstate.ErrorVariable).Compile();
                return(new EvaluationCallback(o => func(o, false)));
            }
            throw new Exception();
        }
Beispiel #6
0
        private Exp CheckIfZero(CompilerState state, Exp expression)
        {
            if (state == null)
            {
                throw new Exception();
            }
            if (expression == null)
            {
                throw new Exception();
            }

            if (expression.Type == typeof(int))
            {
                var constructor = typeof(Exception).GetConstructor(new Type[] { typeof(string) });
                return(Exp.Block(
                           Exp.IfThen(Exp.Equal(expression, Exp.Constant(0)),
                                      Exp.Throw(Exp.New(constructor, Exp.Constant("Division by zero")))),
                           expression));
            }

            if (expression.Type == typeof(float))
            {
                var constructor = typeof(Exception).GetConstructor(new Type[] { typeof(string) });
                return(Exp.Block(
                           Exp.IfThen(Exp.Equal(expression, Exp.Constant(0.0f)),
                                      Exp.Throw(Exp.New(constructor, Exp.Constant("Division by zero")))),
                           expression));
            }
            return(expression);
        }
Beispiel #7
0
        public static Expression ToSet(Expression arg)
        {
            var valueType = GetEnumerableValueType(arg);
            var setType   = typeof(HashSet <>).MakeGenericType(valueType);
            var ctor      = setType.GetConstructor(new [] { typeof(IEnumerable <>).MakeGenericType(valueType) });

            return(new Expression(LinqExpression.New(ctor, arg)));
        }
Beispiel #8
0
        public static Expression CreateSet(HashSet <Expression> values)
        {
            var valueType = values.First().Type;
            var setType   = typeof(HashSet <>).MakeGenericType(valueType);
            var ctor      = setType.GetConstructor(new [] { typeof(IEnumerable <>).MakeGenericType(valueType) });
            var args      = LinqExpression.NewArrayInit(valueType, values.Select(x => x.internalExpression));

            return(new Expression(LinqExpression.New(ctor, args)));
        }
        public void MemberInit_no_bindings()
        {
            var expression =
                LinqExpression.MemberInit(
                    LinqExpression.New(
                        typeof(SampleClass)));

            ShouldRoundrip(expression);
        }
        public void Throw_value()
        {
            var expression =
                LinqExpression.Throw(
                    LinqExpression.New(
                        typeof(ArgumentException)));

            ShouldRoundrip(expression);
        }
        private static Func <PluginMetadata, object> MakeCreateFunc(Type type, string name)
        { // TODO: what do i want the visibiliy of Init methods to be?
            var ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
                        .Select(c => (c, attr: c.GetCustomAttribute <InitAttribute>()))
                        .NonNull(t => t.attr)
                        .OrderByDescending(t => t.c.GetParameters().Length)
                        .Select(t => t.c).ToArray();

            if (ctors.Length > 1)
            {
                Logger.loader.Warn($"Plugin {name} has multiple [Init] constructors. Picking the one with the most parameters.");
            }

            bool usingDefaultCtor = false;
            var  ctor             = ctors.FirstOrDefault();

            if (ctor == null)
            { // this is a normal case
                usingDefaultCtor = true;
                ctor             = type.GetConstructor(Type.EmptyTypes);
                if (ctor == null)
                {
                    throw new InvalidOperationException($"{type.FullName} does not expose a public default constructor and has no constructors marked [Init]");
                }
            }

            var initMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                              .Select(m => (m, attr: m.GetCustomAttribute <InitAttribute>()))
                              .NonNull(t => t.attr).Select(t => t.m).ToArray();

            // verify that they don't have lifecycle attributes on them
            foreach (var method in initMethods)
            {
                var attrs = method.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false);
                if (attrs.Length != 0)
                {
                    throw new InvalidOperationException($"Method {method} on {type.FullName} has both an [Init] attribute and a lifecycle attribute.");
                }
            }

            var metaParam  = Expression.Parameter(typeof(PluginMetadata), "meta");
            var objVar     = ExpressionEx.Variable(type, "objVar");
            var persistVar = ExpressionEx.Variable(typeof(object), "persistVar");
            var createExpr = Expression.Lambda <Func <PluginMetadata, object> >(
                ExpressionEx.Block(new[] { objVar, persistVar },
                                   initMethods
                                   .Select(m => PluginInitInjector.InjectedCallExpr(m.GetParameters(), metaParam, persistVar, es => Expression.Call(objVar, m, es)))
                                   .Prepend(ExpressionEx.Assign(objVar,
                                                                usingDefaultCtor
                                ? Expression.New(ctor)
                                : PluginInitInjector.InjectedCallExpr(ctor.GetParameters(), metaParam, persistVar, es => Expression.New(ctor, es))))
                                   .Append(Expression.Convert(objVar, typeof(object)))),
                metaParam);

            // TODO: since this new system will be doing a f**k load of compilation, maybe add FastExpressionCompiler
            return(createExpr.Compile());
        }
        public void Call_Method_Instance()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    typeof(SampleClass).GetMethod(nameof(SampleClass.InstanceMethod)));

            ShouldRoundrip(expression);
        }
            public LambdaExpression Creator(Type t)
            {
                var valueType = GetValueType(t);
                var inner     = Ex.Parameter(typeof(IReadOnlyDictionary <,>).MakeGenericType(typeof(string), valueType), "inner");

                return(Ex.Lambda(
                           Ex.New(
                               typeof(ReadOnlyDictionaryRecord <>).MakeGenericType(valueType).GetTypeInfo().DeclaredConstructors.First(),
                               inner), inner));
            }
        public void Call_Method_Instance_TypeArguments()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    typeof(SampleClass).GetMethod(nameof(SampleClass.GenericInstanceMethod)).MakeGenericMethod(typeof(object)));

            ShouldRoundrip(expression);
        }
        public void Call_Method_Instance_Arguments()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    typeof(SampleClass).GetMethod(nameof(SampleClass.InstanceMethodWithArgument)),
                    LinqExpression.Constant(0L));

            ShouldRoundrip(expression);
        }
        public void Call_Default()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    nameof(SampleClass.InstanceMethod),
                    Array.Empty <Type>(),
                    Array.Empty <LinqExpression>());

            ShouldRoundrip(expression);
        }
        public void ListInit()
        {
            var expression =
                LinqExpression.ListInit(
                    LinqExpression.New(
                        typeof(List <long>)),
                    LinqExpression.ElementInit(
                        typeof(List <long>).GetMethod("Add"),
                        LinqExpression.Constant(0L)));

            ShouldRoundrip(expression);
        }
        public void MemberInit_bind()
        {
            var expression =
                LinqExpression.MemberInit(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    LinqExpression.Bind(
                        typeof(SampleClass).GetField(nameof(SampleClass.InstanceField)),
                        LinqExpression.Constant(string.Empty)));

            ShouldRoundrip(expression);
        }
Beispiel #19
0
        void ConvertArgumentToParamType(List <Argument> arguments, ParameterInfo[] parameters, out Expr failExpr)
        {
            failExpr = null;

            for (int i = 0; i < arguments.Count; i++)
            {
                var arg   = arguments[i];
                var param = parameters[i];

                if (param.ParameterType == typeof(bool) && arg.Type != typeof(bool))
                {
                    arg.Expression = ExprHelpers.ConvertToBoolean(context, arg.Expression);
                }
                else if (param.ParameterType == typeof(double) && arg.Type == typeof(string))
                {
                    arg.Expression = ExprHelpers.ConvertToNumberAndCheck(
                        context, arg.Expression,
                        ExceptionMessage.INVOKE_BAD_ARGUMENT_GOT, i + 1, "number", "string");
                }
                else if (param.ParameterType == typeof(string) && arg.Type != typeof(string))
                {
                    arg.Expression = Expr.Call(arg.Expression, MemberInfos.ObjectToString, arg.Expression);
                }
                else
                {
                    if (arg.Type == param.ParameterType || arg.Type.IsSubclassOf(param.ParameterType))
                    {
                        arg.Expression = Expr.Convert(arg.Expression, param.ParameterType);
                    }
                    else
                    {
                        Func <Expr, Expr> typeNameExpr =
                            obj => Expr.Invoke(
                                Expr.Constant((Func <object, string>)BaseLibrary.Type),
                                Expr.Convert(obj, typeof(object)));

                        // Ugly reflection hack
                        failExpr = Expr.Throw(
                            Expr.New(
                                MemberInfos.NewRuntimeException,
                                Expr.Constant(ExceptionMessage.INVOKE_BAD_ARGUMENT_GOT),
                                Expr.NewArrayInit(
                                    typeof(object),
                                    Expr.Constant(i + 1, typeof(object)),
                                    typeNameExpr(Expr.Constant(Activator.CreateInstance(param.ParameterType))),
                                    typeNameExpr(arg.Expression))));
                        break;
                    }
                }
            }
        }
        public void MemberInit_list_bind()
        {
            var expression =
                LinqExpression.MemberInit(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    LinqExpression.ListBind(
                        typeof(SampleClass).GetProperty(nameof(SampleClass.ListProperty)),
                        LinqExpression.ElementInit(
                            typeof(List <long>).GetMethod("Add"),
                            LinqExpression.Constant(0L))));

            ShouldRoundrip(expression);
        }
            public LambdaExpression Creator(Type t)
            {
                var valueType = GetValueType(t);
                var inner     = Ex.Parameter(typeof(IDictionary <,>).MakeGenericType(typeof(string), valueType), "inner");

                return(Ex.Lambda(
                           Ex.Condition(
                               Ex.Property(Ex.Convert(inner, typeof(ICollection <>).MakeGenericType(typeof(KeyValuePair <,>).MakeGenericType(typeof(string), valueType))),
                                           nameof(ICollection <object> .IsReadOnly)),
                               Ex.Default(typeof(DictionaryRecord <>).MakeGenericType(valueType)),
                               Ex.New(
                                   typeof(DictionaryRecord <>).MakeGenericType(valueType).GetTypeInfo().DeclaredConstructors.First(),
                                   inner)), inner));
            }
Beispiel #22
0
        void CheckNumberOfArguments(List <Argument> arguments, ParameterInfo[] parameters, out Expr failExpr)
        {
            failExpr = null;
            Debug.Assert(arguments.Count <= parameters.Length);

            if (arguments.Count < parameters.Length)
            {
                failExpr = Expr.Throw(
                    Expr.New(
                        MemberInfos.NewRuntimeException,
                        Expr.Constant(ExceptionMessage.INVOKE_BAD_ARGUMENT_EXPECTED),
                        Expr.Constant(new object[] { arguments.Count + 1, "value" })));
            }
        }
        public void Call_Default_Arguments()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    nameof(SampleClass.InstanceMethodWithArgument),
                    Array.Empty <Type>(),
                    new[]
            {
                LinqExpression.Constant(0L),
            });

            ShouldRoundrip(expression);
        }
        public void Call_Default_TypeArguments()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    nameof(SampleClass.GenericInstanceMethod),
                    new[]
            {
                typeof(object),
            },
                    Array.Empty <LinqExpression>());

            ShouldRoundrip(expression);
        }
        private LambdaExpression constructionLambda(Type from, Type to)
        {
            var valueType = recordCreator.GetValueType(from);
            var recType   = typeof(IRecord <>).MakeGenericType(valueType);
            var tryGet    = recType.GetTypeInfo().GetDeclaredMethod(nameof(IRecord <object> .TryGetValue));

            var input = Ex.Parameter(from, "input");
            var rec   = Ex.Parameter(recType, "rec");
            var ctor  = GetConstructorForType(to);
            var tmp   = Ex.Parameter(valueType, "tmp");
            var pars  = ctor.GetParameters().Select((p, i) => new
            {
                Converter = Ref.GetLambda(valueType, p.ParameterType),
                Var       = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p.ParameterType), p.Name),
                Type      = p.ParameterType,
                Optional  = p.GetCustomAttributes <OptionalAttribute>().Any(),
                Default   = p.HasDefaultValue ? p.DefaultValue : p.ParameterType.GetTypeInfo().IsValueType ? Activator.CreateInstance(p.ParameterType) : null
            }).ToArray();
            var end   = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end");
            var block = Ex.Block(new[] { rec }.Concat(pars.Select(x => x.Var)),
                                 Ex.Assign(rec, recordCreator.Creator(from).ApplyTo(input)),
                                 Ex.Block(new[] { tmp }, pars
                                          .Select(x =>
                                                  x.Optional
                        ? Ex.Block(
                                                      Ex.IfThenElse(
                                                          Ex.MakeBinary(ExpressionType.OrElse,
                                                                        Ex.Call(rec, tryGet, Ex.Constant(x.Var.Name), tmp),
                                                                        Ex.Call(rec, tryGet, Ex.Constant(ToPascalCase(x.Var.Name)), tmp)),
                                                          Ex.Block(
                                                              Ex.Assign(x.Var, x.Converter.ApplyTo(tmp)),
                                                              Ex.IfThen(Ex.Not(Ex.Property(x.Var, nameof(IConversionResult.IsSuccessful))),
                                                                        Ex.Goto(end, NoResult(to)))),
                                                          Ex.Assign(x.Var, Result(x.Type, Ex.Constant(x.Default, x.Type)))))
                        : Ex.Block(
                                                      Ex.IfThen(Ex.Not(Ex.Call(rec, tryGet, Ex.Constant(x.Var.Name), tmp)),
                                                                Ex.IfThen(Ex.Not(Ex.Call(rec, tryGet, Ex.Constant(ToPascalCase(x.Var.Name)), tmp)),
                                                                          Ex.Goto(end, NoResult(to)))),
                                                      Ex.Assign(x.Var, x.Converter.ApplyTo(tmp)),
                                                      Ex.IfThen(Ex.Not(Ex.Property(x.Var, nameof(IConversionResult.IsSuccessful))),
                                                                Ex.Goto(end, NoResult(to)))))),
                                 Ex.Label(end, Result(to, Ex.New(ctor, pars.Select(p => Ex.Property(p.Var, nameof(IConversionResult.Result)))))));

            return(Ex.Lambda(block, input));
        }
Beispiel #26
0
        public Expression /*!*/ MakeAllocatorCall(CallArguments /*!*/ args, Func <Expression> /*!*/ defaultExceptionMessage)
        {
            Type type = GetUnderlyingSystemType();

            if (_structInfo != null)
            {
                return(Methods.AllocateStructInstance.OpCall(AstUtils.Convert(args.TargetExpression, typeof(RubyClass))));
            }

            if (type.IsSubclassOf(typeof(Delegate)))
            {
                return(MakeDelegateConstructorCall(type, args));
            }

            ConstructorInfo ctor;

            if (IsException())
            {
                if ((ctor = type.GetConstructor(new[] { typeof(string) })) != null)
                {
                    return(Ast.New(ctor, defaultExceptionMessage()));
                }
                else if ((ctor = type.GetConstructor(new[] { typeof(string), typeof(Exception) })) != null)
                {
                    return(Ast.New(ctor, defaultExceptionMessage(), Ast.Constant(null)));
                }
            }

            if ((ctor = type.GetConstructor(new[] { typeof(RubyClass) })) != null)
            {
                return(Ast.New(ctor, AstUtils.Convert(args.TargetExpression, typeof(RubyClass))));
            }

            if ((ctor = type.GetConstructor(new[] { typeof(RubyContext) })) != null)
            {
                return(Ast.New(ctor, args.ContextExpression));
            }

            if ((ctor = type.GetConstructor(Type.EmptyTypes)) != null)
            {
                return(Ast.New(ctor));
            }

            throw RubyExceptions.CreateTypeError(String.Format("allocator undefined for {0}", Name));
        }
Beispiel #27
0
        void OverflowIntoParams(List <Argument> arguments, ParameterInfo[] parameters)
        {
            if (arguments.Count == 0 || parameters.Length == 0)
            {
                return;
            }

            var overflowingArgs = arguments.Skip(parameters.Length - 1).ToList();
            var lastParam       = parameters.Last();

            if (overflowingArgs.Count == 1 && overflowingArgs[0].Type == lastParam.ParameterType)
            {
                return;
            }

            Expr argExpr;

            if (lastParam.IsParams())
            {
                var elementType = lastParam.ParameterType.GetElementType();
                if (overflowingArgs.Any(arg => arg.Type != elementType && !arg.Type.IsSubclassOf(elementType)))
                {
                    return;
                }

                argExpr = Expr.NewArrayInit(
                    elementType,
                    overflowingArgs.Select(arg => Expr.Convert(arg.Expression, elementType)));
            }
            else if (lastParam.ParameterType == typeof(Varargs))
            {
                argExpr = Expr.New(
                    MemberInfos.NewVarargs,
                    Expr.NewArrayInit(
                        typeof(object),
                        overflowingArgs.Select(arg => Expr.Convert(arg.Expression, typeof(object)))));
            }
            else
            {
                return;
            }

            arguments.RemoveRange(arguments.Count - overflowingArgs.Count, overflowingArgs.Count);
            arguments.Add(new Argument(argExpr, lastParam.ParameterType));
        }
        public void Call_Instance_TypeArgumentss_Arguments()
        {
            var expression =
                LinqExpression.Call(
                    LinqExpression.New(
                        typeof(SampleClass)),
                    nameof(SampleClass.GenericInstanceMethodWithArgument),
                    new[]
            {
                typeof(object),
            },
                    new[]
            {
                LinqExpression.Constant(0L),
            });

            ShouldRoundrip(expression);
        }
Beispiel #29
0
            public Expression CreateInitExpression()
            {
                List <MemberBinding> bindings = new List <MemberBinding>();

                var modelType    = ((PropertyInfo)ModelProperty.Member).PropertyType;
                var responseType = ResponseProperty.PropertyType;
                var props        = responseType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.CanWrite);

                foreach (var p in props)
                {
                    IncludeTree include;
                    Expression  bind = null;

                    if (!Includes.TryGetValue(p.Name, out include))
                    {
                        NavigationPropertyAttribute navAttr = p.GetCustomAttribute <NavigationPropertyAttribute>();

                        if (navAttr != null)
                        {
                            var navModelProp = Expression.Property(ModelProperty, modelType.GetProperty(navAttr.NavigationProperty));
                            var navProp      = Expression.Property(navModelProp, ((PropertyInfo)navModelProp.Member).PropertyType.GetProperty(navAttr.Property));
                            bind = navProp;
                        }
                        else if (IsMappeable(p))
                        {
                            bind = Expression.Property(ModelProperty, modelType.GetProperty(p.Name));
                        }
                    }
                    else
                    {
                        bind = include.CreateInitExpression();
                    }

                    if (bind != null)
                    {
                        bindings.Add(Expression.Bind(p, bind));
                    }
                }

                NewExpression        newResponse    = Expression.New(responseType);
                MemberInitExpression initExpression = Expression.MemberInit(newResponse, bindings);

                return(initExpression);
            }
Beispiel #30
0
        // Pseudocode:
        //I input =>
        //{
        //  var i = (UI)input;
        //  var result = new char[base64sizeof(UI)];
        //  for (int j = 0; j == 0 || i > 0; j++)
        //  {
        //      result[j] = _mapChar[i & 0x3f];
        //      i >>= 6;
        //  }
        //}
        private LambdaExpression toLambda(Type from)
        {
            var input     = Ex.Parameter(from, "input");
            var result    = Ex.Parameter(typeof(char[]), "result");
            var i         = workingType(from) == from ? input : Ex.Parameter(workingType(from), "i");
            var j         = Ex.Parameter(typeof(int), "j");
            var loopstart = Ex.Label("loopstart");
            var loopend   = Ex.Label("loopend");

            var loop = Ex.Block(
                Ex.Label(loopstart),
                Ex.IfThen(Ex.MakeBinary(ExpressionType.AndAlso,
                                        Ex.MakeBinary(ExpressionType.GreaterThan, j, Ex.Constant(0)),
                                        i.Type == typeof(BigInteger)
                        ? (Ex)Ex.Call(i, nameof(BigInteger.Equals), Type.EmptyTypes, Ex.Constant(BigInteger.Zero))
                        : Ex.MakeBinary(ExpressionType.Equal, i, Ex.Convert(Ex.Constant(0), i.Type))),
                          Ex.Goto(loopend)),
                Ex.Assign(
                    Ex.ArrayAccess(result, j),
                    Ex.ArrayIndex(Ex.Constant(_mapChars),
                                  Ex.Convert(Ex.MakeBinary(ExpressionType.And, i, Ex.Convert(Ex.Constant(0x3f), i.Type)), typeof(int)))),
                Ex.RightShiftAssign(i, Ex.Constant(6)),
                Ex.PostIncrementAssign(j),
                Ex.Goto(loopstart));
            var ret = Result(typeof(string),
                             Ex.New(typeof(string).GetTypeInfo().DeclaredConstructors
                                    .Select(c => new { c, p = c.GetParameters() })
                                    .First(c => c.p.Length == 3 && c.p[0].ParameterType == typeof(char[]) && c.p[1].ParameterType == typeof(int) && c.p[2].ParameterType == typeof(int)).c,
                                    result, Ex.Constant(0), j));
            var block = Ex.Block(Ex.Assign(j, Ex.Constant(0)),
                                 Ex.Assign(result, Ex.NewArrayBounds(typeof(char), Ex.Constant(charbound(from)))),
                                 loop,
                                 Ex.Label(loopend),
                                 ret);

            block = input == i
                ? Ex.Block(new[] { j, result },
                           block)
                : Ex.Block(new[] { i, j, result },
                           Ex.Assign(i, Ex.Convert(input, i.Type)),
                           block);

            return(Ex.Lambda(block, input));
        }