Call() public static method

Creates a MethodCallExpression that represents a call to a method that takes no arguments.
public static Call ( Expression instance, MethodInfo method ) : MethodCallExpression
instance Expression An that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).
method System.Reflection.MethodInfo The that represents the target method.
return MethodCallExpression
        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());
        }
Exemplo n.º 2
0
        public static InvocationShape CreateFrom(Invocation invocation)
        {
            var method = invocation.Method;

            Expression[] arguments;
            {
                var parameterTypes = method.GetParameterTypes();
                var n = parameterTypes.Count;
                arguments = new Expression[n];
                for (int i = 0; i < n; ++i)
                {
                    arguments[i] = E.Constant(invocation.Arguments[i], parameterTypes[i]);
                }
            }

            LambdaExpression expression;

            {
                var mock = E.Parameter(method.DeclaringType, "mock");
                expression = E.Lambda(E.Call(mock, method, arguments).Apply(UpgradePropertyAccessorMethods.Rewriter), mock);
            }

            if (expression.IsProperty())
            {
                var property = expression.ToPropertyInfo();
                Guard.CanRead(property);

                Debug.Assert(property.CanRead(out var getter) && method == getter);
            }

            return(new InvocationShape(expression, method, arguments, exactGenericTypeArguments: true));
        }
        protected override ExpressionBody Transform(CallExpression lx)
        {
            if (!_nameResolver.TryResolveFunctionName(lx.OperatorName, out var m))
            {
                throw new ArgumentException($"The function name `{lx.OperatorName}` was not recognized.");
            }

            var parameterCount = m.GetParameters().Count(pi => pi.ParameterType == typeof(LogEventPropertyValue));

            if (parameterCount != lx.Operands.Length)
            {
                throw new ArgumentException($"The function `{lx.OperatorName}` requires {parameterCount} arguments.");
            }

            var operands = lx.Operands.Select(Transform).ToList();

            // `and` and `or` short-circuit to save execution time; unlike the earlier Serilog.Filters.Expressions, nothing else does.
            if (Operators.SameOperator(lx.OperatorName, Operators.RuntimeOpAnd))
            {
                return(CompileLogical(LX.AndAlso, operands[0], operands[1]));
            }

            if (Operators.SameOperator(lx.OperatorName, Operators.RuntimeOpOr))
            {
                return(CompileLogical(LX.OrElse, operands[0], operands[1]));
            }

            if (m.GetParameters().Any(pi => pi.ParameterType == typeof(StringComparison)))
            {
                operands.Insert(0, LX.Constant(lx.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));
            }

            return(LX.Call(m, operands));
        }
        private LambdaExpression fromEnumerableLambda(Type from)
        {
            var input = Ex.Parameter(from, "input");
            var eType = from.GetTypeInfo().ImplementedInterfaces
                        .Where(i => i.GenericTypeArguments.Length == 1 && i.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                        .Select(i => i.GenericTypeArguments[0]).SingleOrDefault()
                        ?? from.GetTypeInfo().GenericTypeArguments[0];
            var res    = Ex.Parameter(typeof(string), "res");
            var result = Ex.Block(new[] { res },
                                  Ex.Assign(res, Ex.Call((from mi in typeof(string).GetTypeInfo().GetDeclaredMethods(nameof(string.Join))
                                                          where mi.GetGenericArguments().Length == 1
                                                          let par = mi.GetParameters()
                                                                    where par.Length == 2 &&
                                                                    par[0].ParameterType == typeof(string) &&
                                                                    par[1].ParameterType == typeof(IEnumerable <>).MakeGenericType(mi.GetGenericArguments()[0])
                                                                    select mi).Single().MakeGenericMethod(eType),
                                                         Ex.Constant(Separators[0].ToString()), input)),
                                  Ex.Condition(Ex.MakeBinary(Et.Equal, Ex.Property(res, nameof(string.Length)), Ex.Constant(0)),
                                               NoResult(typeof(string)),
                                               Result(typeof(string), res)));

            var block = Ex.Condition(Ex.MakeBinary(Et.Equal, input, Ex.Default(from)),
                                     NoResult(typeof(string)),
                                     result);
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
        protected override ExpressionBody Transform(IndexOfMatchExpression mx)
        {
            var rx     = LX.Constant(mx.Regex);
            var target = Transform(mx.Corpus);

            return(LX.Call(IndexOfMatchMethod, target, rx));
        }
Exemplo n.º 6
0
        public static IQueryable <TEntity> EagerFetchAll <TEntity>(this IQueryable <TEntity> query)
        {
            // hack the session reference out of the provider - or is
            // there a better way to do this?
            //IStatelessSession session = (IStatelessSession)query.Provider.GetType().GetProperty("Session").GetValue(query.Provider);

            //ISession session = (ISession)query.Provider.GetType()
            //                             .GetProperty("Session", System.Reflection.BindingFlags.Instance
            //                                                   | System.Reflection.BindingFlags.NonPublic)
            //                             .GetValue(query.Provider);

            var            entityType     = typeof(TEntity);
            var            sessionFactory = Ioc.Create <ISessionFactory>();
            IClassMetadata metaData       = sessionFactory.GetClassMetadata(entityType);

            for (int i = 0; i < metaData.PropertyNames.Length; i++)
            {
                global::NHibernate.Type.IType propType = metaData.PropertyTypes[i];

                // get eagerly mapped associations to other entities
                if (propType.IsAssociationType && !metaData.PropertyLaziness[i])
                {
                    ParameterExpression par = Expression.Parameter(entityType, "p");

                    Expression propExp = Expression.Property(par, metaData.PropertyNames[i]);



                    Type             relatedType = null;
                    LambdaExpression lambdaExp;
                    string           methodName;
                    if (propType.ReturnedClass.IsGenericCollection())
                    {
                        relatedType = propType.ReturnedClass.GetGenericArguments()[0];
                        var funcType = typeof(Func <,>).MakeGenericType(entityType, typeof(IEnumerable <>).MakeGenericType(relatedType));
                        lambdaExp  = Expression.Lambda(funcType, propExp, par);
                        methodName = "FetchMany";
                    }
                    else
                    {
                        relatedType = propType.ReturnedClass;
                        lambdaExp   = Expression.Lambda(propExp, par);
                        methodName  = "Fetch";
                    }

                    var        fetchManyMethodImpl = typeof(EagerFetchingExtensionMethods).GetMethod(methodName).MakeGenericMethod(entityType, relatedType);
                    Expression callExpr            = Expression.Call(null,
                                                                     fetchManyMethodImpl,
                                                                     // first parameter is the query, second is property access expression
                                                                     query.Expression, lambdaExp
                                                                     );

                    LambdaExpression expr             = Expression.Lambda(callExpr, par);
                    Type             fetchGenericType = typeof(NhFetchRequest <,>).MakeGenericType(entityType, propType.ReturnedClass);
                    query = (IQueryable <TEntity>)Activator.CreateInstance(fetchGenericType, query.Provider, callExpr);
                }
            }

            return(query);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Filters a sequence of values based on a fulltext search predicate
        /// </summary>
        /// <typeparam name="T">Any type</typeparam>
        /// <param name="source">The source - some IQueryable object.</param>
        /// <param name="text">The text - meaning of the search</param>
        /// <param name="options">The options for full-text search</param>
        /// <returns></returns>
        public static IQueryable <T> FullTextSearchQuery <T>(this IQueryable <T> source, string text, FullTextSearchOptions options = null)
        {
            var pe            = Exp.Parameter(typeof(T), "d");
            var predicateBody = CreateSubExpression(pe, typeof(T), text, options, isQueriable: true);

            if (predicateBody != null)
            {
                var whereExp = Exp.Lambda <Func <T, bool> >(predicateBody, new ParameterExpression[] { pe });
                source = source.Where(whereExp);
            }

            //Order by Expression
            if (options == null)
            {
                return(source);
            }

            var orderByProperty = options.OrderBy;

            if (string.IsNullOrEmpty(orderByProperty))
            {
                orderByProperty = typeof(T).GetProperties().First().Name;
            }

            var property   = Exp.Property(pe, orderByProperty);
            var lambda     = Exp.Lambda(property, pe);
            var method     = options.IsDescendingOrder ? "OrderByDescending" : "OrderBy";
            var orderByExp = Exp.Call(typeof(Queryable), method, new[] { typeof(T), property.Type }, source.Expression, lambda);

            source = source.Provider.CreateQuery <T>(orderByExp) as IOrderedQueryable <T>;
            return(source);
        }
Exemplo n.º 8
0
        private Expression ReplaceQueryable(Expression expression, object value)
        {
            MethodCallExpression mc = expression as MethodCallExpression;

            if (mc != null)
            {
                Expression[] args = mc.Arguments.ToArray();
                Expression   narg = ReplaceQueryable(mc.Arguments[0], value);
                if (narg != args[0])
                {
                    args[0] = narg;
                    return(Expression.Call(mc.Method, args));
                }
                else
                {
                    return(mc);
                }
            }

            ConstantExpression c = expression as ConstantExpression;

            if (c != null && c.Type.GetInterfaces().Contains(typeof(IQueryable)))
            {
                return(Expression.Constant(value));
            }

            return(expression);
        }
Exemplo n.º 9
0
        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));
        }
Exemplo n.º 10
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();
        }
Exemplo n.º 11
0
        public LambdaExpression CreateLambda(Type from, Type to)
        {
            var fromParameters = from.GetTypeInfo().GenericTypeArguments;
            var toParameters   = to.GetTypeInfo().GenericTypeArguments;

            var converters = fromParameters
                             .Zip(toParameters, (f, t) => Ref.GetLambda(f, t))
                             .ToArray();
            var input = Ex.Parameter(from, "input");

            var res = toParameters.Select(t => Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(t))).ToArray();

            var conversion = res.Select((r, i) =>
                                        Ex.Assign(res[i], converters[i].ApplyTo(Ex.PropertyOrField(input, $"Item{i + 1}")))).ToArray();
            var conversionSuccesful = Enumerable.Aggregate(res, (Ex)Ex.Constant(true),
                                                           (c, p) => Ex.MakeBinary(Et.AndAlso, c, Ex.Property(p, nameof(IConversionResult.IsSuccessful))));

            var block = Ex.Block(res,
                                 Ex.Block(conversion),
                                 Ex.Condition(conversionSuccesful,
                                              Result(to,
                                                     Ex.Call(Creator(to), Enumerable.Select(res, p => Ex.Property(p, nameof(IConversionResult.Result))))),
                                              NoResult(to)));
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
        public LambdaExpression CreateLambda(Type from, Type to)
        {
            var toParameters = to.GetTypeInfo().GenericTypeArguments;
            var tupa         = toParameters.Length;
            var input        = Ex.Parameter(from, "input");
            var converters   = toParameters.Select(p => Ref.GetLambda(typeof(string), p)).ToArray();
            var res          = toParameters.Select(p => Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p))).ToArray();
            var end          = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end");
            var indexer      = typeof(string[]).GetTypeInfo().GetDeclaredProperty("Item");

            var split      = Ex.Parameter(typeof(string[]), "split");
            var conversion = Ex.Block(converters.Select((c, i) =>
                                                        Ex.Block(
                                                            Ex.Assign(res[i],
                                                                      c.ApplyTo(Ex.MakeIndex(split, indexer, new[] { Ex.MakeBinary(Et.Add, Ex.Constant(i), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))) }))),
                                                            Ex.IfThen(Ex.Not(Ex.Property(res[i], nameof(IConversionResult.IsSuccessful))),
                                                                      Ex.Goto(end, NoResult(to))))));
            var block = Ex.Block(new[] { split },
                                 Ex.Assign(split, Ex.Call(input, nameof(string.Split), Type.EmptyTypes, _separator)),
                                 Ex.Condition(Ex.MakeBinary(Et.LessThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)),
                                              NoResult(to),
                                              Ex.Block(res,
                                                       Ex.IfThen(Ex.MakeBinary(Et.GreaterThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)),
                                                                 Ex.Assign(Ex.ArrayAccess(split, Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))),
                                                                           Ex.Call(typeof(string), nameof(string.Join), Type.EmptyTypes, _separatorString,
                                                                                   Ex.Call(typeof(Enumerable), nameof(Enumerable.Take), new[] { typeof(string) }, split,
                                                                                           Ex.MakeBinary(Et.Add, Ex.Constant(1), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))))))),
                                                       conversion,
                                                       Ex.Label(end, Result(to, Ex.Call(Creator(to), res.Select(r => Ex.Property(r, nameof(IConversionResult.Result)))))))));
            var lambda = Ex.Lambda(block, input);

            return(lambda);
        }
Exemplo n.º 13
0
        private static TSetLambda CreateSetter <TGetLambda, TSetLambda>(
            this Expression <TGetLambda> getter,
            Type propertyType)
        {
            var memberExpression = (MemberExpression)getter.Body;
            var property         = (PropertyInfo)memberExpression.Member;
            var setMethod        = property.GetSetMethod();

            if (setMethod == null)
            {
                return(default(TSetLambda));
            }

            var parameterValue = Expression.Parameter(propertyType);

            var callParameter =
                Equals(propertyType, memberExpression.Type)
                ? (Expression)parameterValue
                : Expression.Convert(parameterValue, memberExpression.Type);

            var newExpression = Expression.Lambda <TSetLambda>(
                Expression.Call(memberExpression.Expression, setMethod, callParameter),
                getter.Parameters.Concat(new[] { parameterValue })
                );

            return(newExpression.Compile());
        }
Exemplo n.º 14
0
        public static Expression Call(ProcedureCall call)
        {
            if (ReferenceEquals(call, null))
            {
                throw new ArgumentNullException(nameof(call));
            }
            var services  = Services.Instance;
            var procedure = services.GetProcedureSignature(call);

            if (!procedure.HasReturnType)
            {
                throw new InvalidOperationException(
                          "Cannot use a procedure that does not return a value.");
            }
            var arguments = services.GetArguments(procedure, call.Arguments);

            var servicesExpr      = LinqExpression.Constant(services);
            var executeCallMethod = typeof(Services).GetMethod(
                "ExecuteCall", new[] { typeof(Scanner.ProcedureSignature), typeof(object[]) });
            var procedureExpr = LinqExpression.Constant(procedure);
            var argumentsExpr = LinqExpression.Constant(arguments);

            var result = LinqExpression.Call(
                servicesExpr, executeCallMethod,
                new[] { procedureExpr, argumentsExpr });
            var value = LinqExpression.Convert(
                LinqExpression.Property(result, "Value"), procedure.ReturnType);

            return(new Expression(value));
        }
Exemplo n.º 15
0
        private static Expression MakeComparison(Expression left, string comparison, string value)
        {
            switch (comparison)
            {
            case "==":
                return(MakeBinary(ExpressionType.Equal, left, value));

            case "!=":
                return(MakeBinary(ExpressionType.NotEqual, left, value));

            case ">":
                return(MakeBinary(ExpressionType.GreaterThan, left, value));

            case ">=":
                return(MakeBinary(ExpressionType.GreaterThanOrEqual, left, value));

            case "<":
                return(MakeBinary(ExpressionType.LessThan, left, value));

            case "<=":
                return(MakeBinary(ExpressionType.LessThanOrEqual, left, value));

            case "Contains":
                return(Expression.Call(MakeString(left), "Contains", Type.EmptyTypes,
                                       Expression.Constant(value, typeof(string))));

            case "StartsWith":
            case "EndsWith":
                return(Expression.Call(MakeString(left), comparison, Type.EmptyTypes,
                                       Expression.Constant(value, typeof(string))));

            default:
                throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
            }
        }
Exemplo n.º 16
0
        public static Expression Average(Expression arg)
        {
            CheckIsEnumerable(arg);
            var average = typeof(Enumerable).GetMethod("Average", new [] { arg.Type });

            return(new Expression(LinqExpression.Call(average, arg)));
        }
Exemplo n.º 17
0
        public static Expression Min(Expression arg)
        {
            CheckIsEnumerable(arg);
            var min = typeof(Enumerable).GetMethod("Min", new [] { arg.Type });

            return(new Expression(LinqExpression.Call(min, arg)));
        }
Exemplo n.º 18
0
        public static Expression Sum(Expression arg)
        {
            CheckIsEnumerable(arg);
            var sum = typeof(Enumerable).GetMethod("Sum", new [] { arg.Type });

            return(new Expression(LinqExpression.Call(sum, arg)));
        }
Exemplo n.º 19
0
        public void Call_Method_TypeArguments()
        {
            var expression =
                LinqExpression.Call(
                    typeof(SampleClass).GetMethod(nameof(SampleClass.GenericStaticMethod)).MakeGenericMethod(typeof(object)));

            ShouldRoundrip(expression);
        }
Exemplo n.º 20
0
    /// <summary>
    /// Creates a function that accepts 0 parameters and returns an untyped result
    /// </summary>
    /// <param name="Host">The declaring type instance, if applicable</param>
    /// <returns></returns>
    public Func <object> Func0(object Host = null)
    {
        var instance = Host != null?XPR.Constant(Host) : default(XPR);

        var result = XPR.Convert(XPR.Call(instance, this), typeof(object));

        return(XPR.Lambda <Func <object> >(result).Compile());
    }
Exemplo n.º 21
0
        public static Expression ToList(Expression arg)
        {
            var valueType = GetEnumerableValueType(arg);
            var toList    = typeof(Enumerable).GetMethod("ToList");

            toList = toList.MakeGenericMethod(valueType);
            return(new Expression(LinqExpression.Call(toList, arg)));
        }
Exemplo n.º 22
0
        public void Call_Method()
        {
            var expression =
                LinqExpression.Call(
                    typeof(SampleClass).GetMethod(nameof(SampleClass.StaticMethod)));

            ShouldRoundrip(expression);
        }
Exemplo n.º 23
0
    /// <summary>
    /// Creates a function that accepts 0 parameters returns a typed result
    /// </summary>
    /// <param name="Host">The declaring type instance, if applicable</param>
    /// <typeparam name="X">The result type</typeparam>
    /// <returns></returns>
    public static Func <X> Func <X>(this MethodInfo method, object Host = null)
    {
        var instance = Host != null?XPR.Constant(Host) : default(XPR);

        var callResult = XPR.Call(instance, method);

        return(XPR.Lambda <Func <X> >(callResult).Compile());
    }
Exemplo n.º 24
0
            public Expr ToExpression()
            {
                if (Method.IsStatic)
                {
                    return(Expr.Call(Method, Parameters.Select(p => p.ToExpression())));
                }

                return(Expr.Call(InvocationTarget.ToExpression(), Method, Parameters.Select(p => p.ToExpression())));
            }
Exemplo n.º 25
0
    /// <summary>
    /// Creates a function that accepts 1 typed parameter and returns a typed result
    /// </summary>
    /// <typeparam name="X">The type of the first parameter</typeparam>
    /// <typeparam name="Y">The result type</typeparam>
    /// <param name="Host">An instance of the declaring type, if applicable</param>
    /// <returns></returns>
    public static Func <X, Y> Func <X, Y>(this MethodInfo method, object Host = null)
    {
        var instance = Host != null?XPR.Constant(Host) : default(XPR);

        var src        = XPR.Parameter(typeof(X), "src");
        var callResult = XPR.Call(instance, method, src);

        return(XPR.Lambda <Func <X, Y> >(callResult, src).Compile());
    }
Exemplo n.º 26
0
    /// <summary>
    /// Creates a function that accepts 3 untyped parameters and returns an untyped result
    /// </summary>
    /// <param name="Host">The declaring type instance, if applicable</param>
    /// <returns></returns>
    public Func <object, object, object, object> Func3(object Host = null)
    {
        var instance = Host != null?XPR.Constant(Host) : default;

        var callResult = XPR.Call(null, this, ArgumentExpressions);
        var result     = XPR.Convert(callResult, typeof(object));

        return(XPR.Lambda <Func <object, object, object, object> >(result, GetParameters(3)).Compile());
    }
Exemplo n.º 27
0
        public void Call_Method_Arguments()
        {
            var expression =
                LinqExpression.Call(
                    typeof(SampleClass).GetMethod(nameof(SampleClass.StaticMethodWithArgument)),
                    LinqExpression.Constant(0L));

            ShouldRoundrip(expression);
        }
Exemplo n.º 28
0
    /// <summary>
    /// Creates a function that accepts 2 typed parameters and returns a typed result
    /// </summary>
    /// <typeparam name="X1">The type of the first parameter</typeparam>
    /// <typeparam name="X2">The type of the second parameter</typeparam>
    /// <typeparam name="Y">The result type</typeparam>
    /// <param name="Host">An instance of the declaring type, if applicable</param>
    /// <returns></returns>
    public static Func <X1, X2, Y> Func <X1, X2, Y>(this MethodInfo method, object Host = null)
    {
        var instance = Host != null?XPR.Constant(Host) : default(XPR);

        var x1         = XPR.Parameter(typeof(X1), "x1");
        var x2         = XPR.Parameter(typeof(X2), "x2");
        var callResult = XPR.Call(instance, method, x1, x2);

        return(XPR.Lambda <Func <X1, X2, Y> >(callResult, x1, x2).Compile());
    }
 static ExpressionBody CompileLogical(Func <ExpressionBody, ExpressionBody, ExpressionBody> apply, ExpressionBody lhs, ExpressionBody rhs)
 {
     return(LX.Convert(
                LX.New(
                    typeof(ScalarValue).GetConstructor(new[] { typeof(object) }) !,
                    LX.Convert(apply(
                                   LX.Call(CoerceToScalarBooleanMethod, lhs),
                                   LX.Call(CoerceToScalarBooleanMethod, rhs)), typeof(object))),
                typeof(LogEventPropertyValue)));
 }
Exemplo n.º 30
0
 private static RuleGenerator /*!*/ CreateGetter(int index)
 {
     return(delegate(MetaObjectBuilder /*!*/ metaBuilder, CallArguments /*!*/ args, string /*!*/ name) {
         metaBuilder.Result = Ast.Call(
             Ast.Convert(args.TargetExpression, typeof(RubyStruct)),
             typeof(RubyStruct).GetMethod("GetValue"),
             Ast.Constant(index)
             );
     });
 }
Exemplo n.º 31
0
 static Expression ToNumber(Expression Expression)
 {
     return Expression.Call(LuaEvents_toNumber, Expression);
 }
Exemplo n.º 32
0
 static Expression GetFirstArgumentAsBool(Expression Expression)
 {
     Expression e = GetFirstArgument(Expression);
     return Expression.Call(e, LuaObject_AsBool);
 }
Exemplo n.º 33
0
 static Expression GetAsBool(Expression Expression)
 {
     return Expression.Call(Expression, LuaObject_AsBool);
 }