System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)

Here are the examples of the csharp api System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1274 Examples 7

19 View Source File : DelegateGenerator.cs
License : MIT License
Project Creator : albyho

public Func<List<object>, object> Generate(Expression exp)
        {
            _parameterCount = 0;
            _parametersExpression =
                Expression.Parameter(typeof(List<object>), "parameters");

            var body = this.Visit(exp); // normalize
            if (body.Type != typeof(object))
            {
                body = Expression.Convert(body, typeof(object));
            }

            var lambda = Expression.Lambda<Func<List<object>, object>>(body, _parametersExpression);
            return lambda.Compile();
        }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

static Expression StringLength(Expression o) =>
            CallThis(nameof(StringLengthMethod), Expression.Convert(o, typeof(string)));

19 View Source File : GenericInterface.cs
License : MIT License
Project Creator : Accelerider

private TDelegate GetActionWithParams<TDelegate>(string methodName, params Type[] argTypes)
            {
                var methodInfo = Type.GetMethod(methodName) ?? throw new ArgumentException(nameof(methodName));
                var argTypeList = argTypes.Any() ? argTypes : typeof(TDelegate).GetGenericArguments();
                (ParameterExpression expression, Type type)[] argObjectParameters = argTypeList
                    .Select(item => (Expression.Parameter(typeof(object)), item))
                    .ToArray();

                var method = Expression.Lambda<TDelegate>(
                        Expression.Call(
                            Expression.Constant(_instance),
                            methodInfo,
                            argObjectParameters.Select(item => Expression.Convert(item.expression, item.type))),
                        argObjectParameters.Select(item => item.expression))
                    .Compile();

                return method;
            }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private DynamicMetaObject CallMethodReturnLast<TBinder> (MethodInfo method, TBinder binder, Expression[] args, Expression value, Fallback<TBinder> fallback)
				where TBinder : DynamicMetaObjectBinder
			{
				//
				// First, call fallback to do default binding
				// This produces either an error or a call to a .NET member
				//
				DynamicMetaObject fallbackResult = fallback (this, binder, null);

				//
				// Build a new expression like:
				// {
				//   object result;
				//   TrySetMember(payload, result = value) ? result : fallbackResult
				// }
				//

				ParameterExpression result = Expression.Parameter (typeof (object), null);
				ParameterExpression callArgs = Expression.Parameter (typeof (object[]), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
						new TrueReadOnlyCollection<Expression> (
							Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										Expression.replacedign (result, Expression.Convert (value, typeof (object)))
									)
								),
								Expression.Block (
									ReferenceArgreplacedign (callArgs, args),
									result
								),
								fallbackResult.Expression,
								typeof (object)
							)
						)
					),
					GetRestrictions ().Merge (fallbackResult.Restrictions)
				);

				//
				// Now, call fallback again using our new MO as the error
				// When we do this, one of two things can happen:
				//   1. Binding will succeed, and it will ignore our call to
				//      the dynamic method, OR
				//   2. Binding will fail, and it will use the MO we created
				//      above.
				//
				return fallback (this, binder, callDynamic);
			}

19 View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela

private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
        {
            //
            // First, call fallback to do default binding
            // This produces either an error or a call to a .NET member
            //
            DynamicMetaObject fallbackResult = fallback(null);

            //
            // Build a new expression like:
            // {
            //   object result;
            //   TrySetMember(payload, result = value) ? result : fallbackResult
            // }
            //
            ParameterExpression result = Expression.Parameter(typeof(object), null);

            IList<Expression> callArgs = new List<Expression>();
            callArgs.Add(Expression.Convert(Expression, typeof(T)));
            callArgs.Add(Constant(binder));
            callArgs.AddRange(args);
            callArgs[args.Length + 1] = Expression.replacedign(result, callArgs[args.Length + 1]);

            DynamicMetaObject callDynamic = new DynamicMetaObject(
                Expression.Block(
                    new[] { result },
                    Expression.Condition(
                        Expression.Call(
                            Expression.Constant(_proxy),
                            typeof(DynamicProxy<T>).GetMethod(methodName),
                            callArgs
                            ),
                        result,
                        fallbackResult.Expression,
                        typeof(object)
                        )
                    ),
                GetRestrictions().Merge(fallbackResult.Restrictions)
                );

            //
            // Now, call fallback again using our new MO as the error
            // When we do this, one of two things can happen:
            //   1. Binding will succeed, and it will ignore our call to
            //      the dynamic method, OR
            //   2. Binding will fail, and it will use the MO we created
            //      above.
            //
            return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private Activator GetActivator(ConstructorInfo constructor)
        {
            var parameters = constructor.GetParameters();

            var parameterExpression = Expression.Parameter(typeof(object[]));
            var argumentExpressions = new Expression[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var indexExpression = Expression.Constant(i);
                var paramType = parameters[i].ParameterType;
                var arrayExpression = Expression.ArrayIndex(parameterExpression, indexExpression);
                var arrayConvertExpression = Expression.Convert(arrayExpression, paramType);
                argumentExpressions[i] = arrayConvertExpression;
            }

            var constructorExpression = Expression.New(constructor, argumentExpressions);
            var constructorConvertExpression = Expression.Convert(constructorExpression, typeof(object));
            var lambdaExpression = Expression.Lambda<Activator>(constructorConvertExpression, parameterExpression);
            var compiledExpression = lambdaExpression.Compile();
            return compiledExpression;
        }

19 View Source File : NodePort.cs
License : MIT License
Project Creator : alelievr

PushDataDelegate CreatePushDataDelegateForEdge(SerializableEdge edge)
		{
			try
			{
				//Creation of the delegate to move the data from the input node to the output node:
				FieldInfo inputField = edge.inputNode.GetType().GetField(edge.inputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
				FieldInfo outputField = edge.outputNode.GetType().GetField(edge.outputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
				Type inType, outType;

#if DEBUG_LAMBDA
				return new PushDataDelegate(() => {
					var outValue = outputField.GetValue(edge.outputNode);
					inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
					outType = edge.outputPort.portData.displayType ?? outputField.FieldType;
					Debug.Log($"Push: {inType}({outValue}) -> {outType} | {owner.name}");

					object convertedValue = outValue;
					if (TypeAdapter.Arereplacedignable(outType, inType))
					{
						var convertionMethod = TypeAdapter.GetConvertionMethod(outType, inType);
						Debug.Log("Convertion method: " + convertionMethod.Name);
						convertedValue = convertionMethod.Invoke(null, new object[]{ outValue });
					}

					inputField.SetValue(edge.inputNode, convertedValue);
				});
#endif

// We keep slow checks inside the editor
#if UNITY_EDITOR
				if (!BaseGraph.TypesAreConnectable(inputField.FieldType, outputField.FieldType))
				{
					Debug.LogError("Can't convert from " + inputField.FieldType + " to " + outputField.FieldType + ", you must specify a custom port function (i.e CustomPortInput or CustomPortOutput) for non-implicit convertions");
					return null;
				}
#endif

				Expression inputParamField = Expression.Field(Expression.Constant(edge.inputNode), inputField);
				Expression outputParamField = Expression.Field(Expression.Constant(edge.outputNode), outputField);

				inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
				outType = edge.outputPort.portData.displayType ?? outputField.FieldType;

				// If there is a user defined convertion function, then we call it
				if (TypeAdapter.Arereplacedignable(outType, inType))
				{
					// We add a cast in case there we're calling the conversion method with a base clreplaced parameter (like object)
					var convertedParam = Expression.Convert(outputParamField, outType);
					outputParamField = Expression.Call(TypeAdapter.GetConvertionMethod(outType, inType), convertedParam);
					// In case there is a custom port behavior in the output, then we need to re-cast to the base type because
					// the convertion method return type is not always replacedignable directly:
					outputParamField = Expression.Convert(outputParamField, inputField.FieldType);
				}
				else // otherwise we cast
					outputParamField = Expression.Convert(outputParamField, inputField.FieldType);

				BinaryExpression replacedign = Expression.replacedign(inputParamField, outputParamField);
				return Expression.Lambda< PushDataDelegate >(replacedign).Compile();
			} catch (Exception e) {
				Debug.LogError(e);
				return null;
			}
		}

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyOrFieldValue(this Type enreplacedyType, object enreplacedy, string propertyName, object value)
    {
        if (enreplacedy == null) return;
        if (enreplacedyType == null) enreplacedyType = enreplacedy.GetType();

        if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
        {
            if (GetPropertiesDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var prop))
            {
                prop.SetValue(enreplacedy, value, null);
                return;
            }
            if (GetFieldsDictIgnoreCase(enreplacedyType).TryGetValue(propertyName, out var field))
            {
                field.SetValue(enreplacedy, value);
                return;
            }
            throw new Exception($"The property({propertyName}) was not found in the type({enreplacedyType.DisplayCsharp()})");
        }

        Action<object, string, object> func = null;
        try
        {
            func = _dicSetPropertyOrFieldValue
                .GetOrAdd(enreplacedyType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyName, pn =>
                {
                    var t = enreplacedyType;
                    MemberInfo memberinfo = enreplacedyType.GetPropertyOrFieldIgnoreCase(pn);
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                            Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    if (memberinfo != null)
                    {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberinfo),
                                Expression.Convert(
                                    parm3,
                                    memberinfo.GetPropertyOrFieldType()
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                });
        }
        catch
        {
            System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
            SetPropertyOrFieldValue(enreplacedyType, enreplacedy, propertyName, value);
            return;
        }
        func(enreplacedy, propertyName, value);
    }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

Expression BuildDependencyItem(string propertyName, object dependencyValue, Expression o)
        {
            return IfThenElseTrue(
                CallThis(nameof(ContainsKey),
                    Expression.Convert(o, typeof(JObject)),
                    Expression.Constant(propertyName)),
                BuildDependencyItem(dependencyValue, o));
        }

19 View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71

private Expression ReduceForEnumerable()
		{
			MethodInfo get_enumerator;
			MethodInfo get_current;

		    ResolveEnumerationMembers(out get_enumerator, out get_current);

			Type enumerator_type = get_enumerator.ReturnType;

			ParameterExpression enumerator = Variable(enumerator_type);

			LabelTarget inner_loop_continue = Label("inner_loop_continue");
			LabelTarget inner_loop_break    = Label("inner_loop_break");

			LabelTarget @continue = ContinueLabel ?? Label("continue");
			LabelTarget @break    = BreakLabel ?? Label("break");

			Expression variable_initializer = Property(enumerator, get_current);

		    if (!Variable.Type.GetTypeInfo().IsreplacedignableFrom(get_current.ReturnType.GetTypeInfo()))
				variable_initializer = Convert(variable_initializer, Variable.Type);

			Expression loop = Block(
				new [] { Variable },
                Goto(@continue),
                Loop(
                    Block(
                        replacedign(Variable, variable_initializer),
                        Body,
                        Label(@continue),
                        Condition(
                            Call(enumerator, Reflection.IEnumerator_MoveNext),
                            Goto(inner_loop_continue),
                            Goto(inner_loop_break)
                        )
                    ),
					inner_loop_break,
					inner_loop_continue
                ),
                Label(@break)
            );

			Expression dispose = CreateDisposeOperation(enumerator_type.GetTypeInfo(), enumerator);

			return Block(
				new [] { enumerator },
                replacedign(enumerator, Call(Enumerable, get_enumerator)),
				dispose != null ? TryFinally(loop, dispose) : loop
            );
		}

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private static Expression ReferenceArgreplacedign (Expression callArgs, Expression[] args)
			{
				ReadOnlyCollectionBuilder<Expression> block = null;

				for (int i = 0; i < args.Length; i++)
				{
					ParameterExpression variable = args[i] as ParameterExpression;

					if (variable.IsByRef)
					{
						if (block == null)
							block = new ReadOnlyCollectionBuilder<Expression> ();

						block.Add (
							Expression.replacedign (
								variable,
								Expression.Convert (
									Expression.ArrayIndex (
										callArgs,
										AstUtils.Constant (i)
									),
									variable.Type
								)
							)
						);
					}
				}

				if (block != null)
					return Expression.Block (block);
				else
					return AstUtils.Empty;
			}

19 View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela

private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
        {
            //
            // Build a new expression like:
            // {
            //   object result;
            //   TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
            // }
            //
            ParameterExpression result = Expression.Parameter(typeof(object), null);

            IList<Expression> callArgs = new List<Expression>();
            callArgs.Add(Expression.Convert(Expression, typeof(T)));
            callArgs.Add(Constant(binder));
            callArgs.AddRange(args);
            callArgs.Add(result);

            DynamicMetaObject resultMetaObject = new DynamicMetaObject(result, BindingRestrictions.Empty);

            // Need to add a conversion if calling TryConvert
            if (binder.ReturnType != typeof(object))
            {
                UnaryExpression convert = Expression.Convert(resultMetaObject.Expression, binder.ReturnType);
                // will always be a cast or unbox

                resultMetaObject = new DynamicMetaObject(convert, resultMetaObject.Restrictions);
            }

            if (fallbackInvoke != null)
            {
                resultMetaObject = fallbackInvoke(resultMetaObject);
            }

            DynamicMetaObject callDynamic = new DynamicMetaObject(
                Expression.Block(
                    new[] { result },
                    Expression.Condition(
                        Expression.Call(
                            Expression.Constant(_proxy),
                            typeof(DynamicProxy<T>).GetMethod(methodName),
                            callArgs
                            ),
                        resultMetaObject.Expression,
                        fallbackResult.Expression,
                        binder.ReturnType
                        )
                    ),
                GetRestrictions().Merge(resultMetaObject.Restrictions).Merge(fallbackResult.Restrictions)
                );

            return callDynamic;
        }

19 View Source File : ExpressionVisitor`1.cs
License : MIT License
Project Creator : 71

protected bool TryVisitUnknown(Expression node, out T result)
        {
            // If reducible, reduce it and visit the reduced node
            if (node.CanReduce)
            {
                result = Visit(node.Reduce());
                return true;
            }

            // If known node, individually modify them
            // ReSharper disable PossibleNullReferenceException
            switch (node.NodeType)
            {
                case ExpressionType.AddChecked:
                    {
                        BinaryExpression binary = node as BinaryExpression;
                        result = Visit(Expression.Add(binary.Left, binary.Right));
                        return true;
                    }
                case ExpressionType.SubtractChecked:
                    {
                        BinaryExpression binary = node as BinaryExpression;
                        result = Visit(Expression.Subtract(binary.Left, binary.Right));
                        return true;
                    }
                case ExpressionType.MultiplyChecked:
                    {
                        BinaryExpression binary = node as BinaryExpression;
                        result = Visit(Expression.Multiply(binary.Left, binary.Right));
                        return true;
                    }
                case ExpressionType.ConvertChecked:
                    {
                        UnaryExpression unary = node as UnaryExpression;
                        result = Visit(Expression.Convert(unary.Operand, unary.Type));
                        return true;
                    }
                case ExpressionType.NegateChecked:
                    {
                        UnaryExpression unary = node as UnaryExpression;
                        result = Visit(Expression.Negate(unary.Operand, unary.Method));
                        return true;
                    }
            }
            // ReSharper restore PossibleNullReferenceException

            result = default(T);
            return false;
        }

19 View Source File : DelegateGenerator.cs
License : MIT License
Project Creator : albyho

protected override Expression VisitConstant(ConstantExpression c)
        {
            Expression exp = Expression.Call(
                _parametersExpression,
                IndexerInfo,
                Expression.Constant(_parameterCount++));
            return c.Type == typeof(object) ? exp : Expression.Convert(exp, c.Type);
        }

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

public static void GenerateDeserializeWithIDictionaryEmptyCtor()
        {
            /*
              var map = MapFormatterHelper.Deserialize(ref reader,ref context);
              if (map == null)
                  return null;
              context.option.Security.DepthStep(ref reader);
              T t = new T();
              Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
              reader = map.Reader; context = map.Context; 
              reader.Seek(map.EndPos);
              context.Depth--;
              return t;  
           */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = new T();
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, Expression.New(t)));
            //MapFormatterHelper.FillData(map,(IDictionary)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 View Source File : ConstructorInvoker.cs
License : MIT License
Project Creator : albyho

private Func<object[], object> InitializeInvoker(ConstructorInfo constructorInfo)
        {
            // Target: (object)new T((T0)parameters[0], (T1)parameters[1], ...)

            // parameters to execute
            var parametersParameter = Expression.Parameter(typeof(object[]), "parameters");

            // build parameter list
            var parameterExpressions = new List<Expression>();
            var paramInfos = constructorInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++)
            {
                // (Ti)parameters[i]
                var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i));
                var valueCast = Expression.Convert(valueObj, paramInfos[i].ParameterType);

                parameterExpressions.Add(valueCast);
            }

            // new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreate = Expression.New(constructorInfo, parameterExpressions);

            // (object)new T((T0)parameters[0], (T1)parameters[1], ...)
            var instanceCreateCast = Expression.Convert(instanceCreate, typeof(object));

            var lambda = Expression.Lambda<Func<object[], object>>(instanceCreateCast, parametersParameter);

            return lambda.Compile();
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static Delegate CreateCaster(Type type)
		{
			var prm = Expression.Parameter(typeof(object), "value");
			//TODO: valuetype vs ref type ?
			var body = Expression.Convert(prm, type);
			var lambda = Expression.Lambda(body, true, prm);
			return lambda.Compile();
		}

19 View Source File : Evaluator.cs
License : MIT License
Project Creator : AlenToma

private Expression Evaluate(Expression e)
            {
                Type type = e.Type;
                if (e.NodeType == ExpressionType.Convert)
                {
                    // check for unnecessary convert & strip them
                    var u = (UnaryExpression)e;
                    if (TypeHelper.GetNonNullableType(u.Operand.Type) == TypeHelper.GetNonNullableType(type))
                    {
                        e = ((UnaryExpression)e).Operand;
                    }
                }
                if (e.NodeType == ExpressionType.Constant)
                {
                    // in case we actually threw out a nullable conversion above, simulate it here
                    // don't post-eval nodes that were already constants
                    if (e.Type == type)
                    {
                        return e;
                    }
                    else if (TypeHelper.GetNonNullableType(e.Type) == TypeHelper.GetNonNullableType(type))
                    {
                        return Expression.Constant(((ConstantExpression)e).Value, type);
                    }
                }
                var me = e as MemberExpression;
                if (me != null)
                {
                    // member accesses off of constant's are common, and yet since these partial evals
                    // are never re-used, using reflection to access the member is faster than compiling  
                    // and invoking a lambda
                    var ce = me.Expression as ConstantExpression;
                    if (ce != null)
                    {
                        return this.PostEval(Expression.Constant(me.Member.GetValue(ce.Value), type));
                    }
                }
                if (type.IsValueType)
                {
                    e = Expression.Convert(e, typeof(object));
                }
                Expression<Func<object>> lambda = Expression.Lambda<Func<object>>(e);
#if NOREFEMIT
                Func<object> fn = ExpressionEvaluator.CreateDelegate(lambda);
#else
                Func<object> fn = lambda.Compile();
#endif
                return this.PostEval(Expression.Constant(fn(), type));
            }

19 View Source File : NativeDecimalGetterHelper.cs
License : MIT License
Project Creator : 1996v

private static Func<Decimal, DecimalBinaryBits> Build()
        {
            ParameterExpression de = Expression.Parameter(typeof(Decimal));
            Expression low, mid, high, flags;
            try
            {
                //FRAMEWORK
                low = Expression.Field(de, typeof(Decimal).GetField("lo", BindingFlags.Instance | BindingFlags.NonPublic));
                mid = Expression.Field(de, typeof(Decimal).GetField("mid", BindingFlags.Instance | BindingFlags.NonPublic));
                high = Expression.Field(de, typeof(Decimal).GetField("hi", BindingFlags.Instance | BindingFlags.NonPublic));
                flags = Expression.Field(de, typeof(Decimal).GetField("flags", BindingFlags.Instance | BindingFlags.NonPublic));
            }
            catch
            {
                try
                {
                    low = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Low", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    mid = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("Mid", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    high = Expression.Convert(Expression.Field(de, typeof(Decimal).GetField("High", BindingFlags.Instance | BindingFlags.NonPublic)), typeof(int));
                    flags = Expression.Field(de, typeof(Decimal).GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic));
                }
                catch (Exception ex)
                {
                    throw BssomSerializationTypeFormatterException.TypeFormatterError(typeof(decimal), ex.Message);
                }
            }

            NewExpression body = Expression.New(typeof(DecimalBinaryBits).GetConstructor(new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) }), low, mid, high, flags);
            return Expression.Lambda<Func<Decimal, DecimalBinaryBits>>(body, de).Compile();
        }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

Expression BuildContent(JSchema schema, Expression o)
        {
            // no content related validation
            if (schema.ContentEncoding == null &&
                schema.ContentMediaType == null)
                return null;

            switch (schema.ContentEncoding)
            {
                case Constants.ContentEncodings.Base64:
                    return
                        IfThenElseTrue(
                            IsTokenType(o, JTokenType.String),
                            CallThis(
                                nameof(ContentBase64),
                                Expression.Convert(o, typeof(string)),
                                Expression.Constant(schema.ContentMediaType, typeof(string))));
                case null:
                    return IfThenElseTrue(
                        IsTokenType(o, JTokenType.String),
                        CallThis(
                            nameof(ContentMediaTypeString),
                            Expression.Convert(o, typeof(string)),
                            Expression.Constant(schema.ContentMediaType, typeof(string))));
                default:
                    return null;
            }
        }

19 View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela

private static Expression[] GetArgs(params DynamicMetaObject[] args)
        {
            return args.Select(arg => Expression.Convert(arg.Expression, typeof(object))).ToArray();
        }

19 View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela

private static Expression[] GetArgArray(DynamicMetaObject[] args, DynamicMetaObject value)
        {
            return new Expression[]
            {
                Expression.NewArrayInit(typeof(object), GetArgs(args)),
                Expression.Convert(value.Expression, typeof(object))
            };
        }

19 View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v

private static Expression BuildSerializeCore(Type type, ObjectSerializationInfo serializationInfo, ParameterExpression instance)
        {
            List<Expression> ary = new List<Expression>();
            LabelTarget returnTarget = Expression.Label(typeof(void), "returnLable");

            if (!type.IsValueType)
            {
                //if (value==null)
                //     writer.WriteNull(); goto label;
                ary.Add(CommonExpressionMeta.Block_IfNullWriteNullWithReturn(instance, type, returnTarget));
            }

            ParameterExpression[] variables = null;
            var keys = serializationInfo.SerializeMemberInfos;
            if (keys.Length == 0)
            {
                //writer.WriteRaw(Array3Cache._EmptyBuffer);
                ary.Add(CommonExpressionMeta.Call_WriteRaw(Expression.Field(null, Array3Cache._EmptyBuffer)));
            }
            else
            {
                int maxLen = keys[keys.Length - 1].KeyIndex + 1;
                Type stackallocBlockType = StackallocBlockProvider.GetOrCreateType(maxLen * sizeof(uint));
                //long position;
                //Block{size} block;
                //IntPtr blockPtr;
                variables = new ParameterExpression[3];
                variables[0] = Expression.Variable(typeof(long), "elementOffPosition");
                variables[1] = Expression.Variable(stackallocBlockType, "block");
                variables[2] = Expression.Variable(typeof(IntPtr),"blockPtr");

                //position = writer.WriteArray3Header(keys.Length);
                ary.Add(Expression.replacedign(variables[0], CommonExpressionMeta.Call_WriteArray3Header(maxLen)));
                //block = new Block{size}();
                ary.Add(Expression.replacedign(variables[1], Expression.New(stackallocBlockType)));
                //blockPtr = AsPointer(ref block);
                ary.Add(Expression.replacedign(variables[2], ExpressionTreeAux.AsPointerExpression(variables[1])));

                //0,3,5  --> maxLen = 6
                FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
                int realIndex = 0;


                for (int i = 0; i < maxLen; i++)
                {
                    //StackallocBlockHelper.WriteUInt(blockPtr, 0, (uint)(writer.Position - position));
                    ary.Add(Expression.Call(null, StackallocBlockHelper._WriteUIntMethodInfo, variables[2], Expression.Constant(i), Expression.Convert(Expression.Subtract(CommonExpressionMeta.Field_WriterPos, variables[0]), typeof(uint))));

                    if (keys[realIndex].KeyIndex != i)
                    {
                        //WriteNull()
                        ary.Add(CommonExpressionMeta.Call_Writer_WriteNull);
                    }
                    else
                    {
                        //Writer(mem.Value)
                        ary.Add(SpecialCodeGenExpression.WriteValues(keys[realIndex], instance, memFormatters));
                        realIndex++;
                    }
                }

                //writer.WriteBackArray3Header(blockPtr)
                ary.Add(CommonExpressionMeta.Call_WriteBackArray3Header(variables[0], variables[2], maxLen));
            }

            ary.Add(Expression.Label(returnTarget));

            if (variables != null)
                return Expression.Block(variables, ary);
            return Expression.Block(ary);
        }

19 View Source File : ExpressionReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

private Expression EnsureCastExpression(Expression expression, Type targetType)
        {
            Type expressionType = expression.Type;

            // check if a cast or conversion is required
            if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsreplacedignableFrom(expressionType)))
            {
                return expression;
            }

            return Expression.Convert(expression, targetType);
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : 71

internal static Expression Convert(this Expression node, Type target)
        {
            if (node.Type == target)
                return node;

            return Expression.Convert(node, target);
        }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private static ReadOnlyCollection<Expression> GetConvertedArgs (params Expression[] args)
			{
				var paramArgs = new Expression[args.Length];

				for (int i = 0; i < args.Length; i++)
				{
					paramArgs[i] = Expression.Convert (args[i], typeof (object));
				}

				return new TrueReadOnlyCollection<Expression> (paramArgs);
			}

19 View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela

private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
        {
            //
            // First, call fallback to do default binding
            // This produces either an error or a call to a .NET member
            //
            DynamicMetaObject fallbackResult = fallback(null);

            IList<Expression> callArgs = new List<Expression>();
            callArgs.Add(Expression.Convert(Expression, typeof(T)));
            callArgs.Add(Constant(binder));
            callArgs.AddRange(args);

            //
            // Build a new expression like:
            //   if (TryDeleteMember(payload)) { } else { fallbackResult }
            //
            DynamicMetaObject callDynamic = new DynamicMetaObject(
                Expression.Condition(
                    Expression.Call(
                        Expression.Constant(_proxy),
                        typeof(DynamicProxy<T>).GetMethod(methodName),
                        callArgs
                        ),
                    Expression.Empty(),
                    fallbackResult.Expression,
                    typeof(void)
                    ),
                GetRestrictions().Merge(fallbackResult.Restrictions)
                );

            //
            // Now, call fallback again using our new MO as the error
            // When we do this, one of two things can happen:
            //   1. Binding will succeed, and it will ignore our call to
            //      the dynamic method, OR
            //   2. Binding will fail, and it will use the MO we created
            //      above.
            //
            return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
        }

19 View Source File : UsingExpression.cs
License : MIT License
Project Creator : 71

public override Expression Reduce()
		{
			var end_finally = Label("end_finally");

			return Block (
				new [] { Variable },
                replacedign(Variable, Disposable),
                TryFinally(
					Body,
                    Block(
                        Condition(
                            NotEqual(Variable, Constant(null)),
                            Block(
								Call(Convert(Variable, typeof(IDisposable)), Reflection.IDisposable_Dispose),
                                Goto(end_finally)
                            ),
                            Goto(end_finally)
                        ),
                        Label(end_finally)
                    )
                )
            );
		}

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private DynamicMetaObject BuildCallMethodWithResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback<TBinder> fallbackInvoke)
				where TBinder : DynamicMetaObjectBinder
			{
				if (!IsOverridden (method))
				{
					return fallbackResult;
				}

				//
				// Build a new expression like:
				// {
				//   object result;
				//   TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
				// }
				//
				ParameterExpression result = Expression.Parameter (typeof (object), null);
				ParameterExpression callArgs = method != DynamicObject_TryBinaryOperation ? Expression.Parameter (typeof (object[]), null) : Expression.Parameter (typeof (object), null);
				ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);

				var resultMO = new DynamicMetaObject (result, BindingRestrictions.Empty);

				// Need to add a conversion if calling TryConvert
				if (binder.ReturnType != typeof (object))
				{
					Debug.replacedert (binder is ConvertBinder && fallbackInvoke == null);

					UnaryExpression convert = Expression.Convert (resultMO.Expression, binder.ReturnType);
					// will always be a cast or unbox
					Debug.replacedert (convert.Method == null);


					// Prepare a good exception message in case the convert will fail
					// JJA - we don't have access to the Strings type:
					//string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotreplacedignable (
					//	"{0}",
					//	this.Value.GetType(),
					//	binder.GetType(),
					//	binder.ReturnType
					//);				
					string convertFailed = $"Dynamic conversion failed: Could not convert type '{Value.WrappedType}' to '{binder.ReturnType}'.";

					Expression condition;
					// If the return type can not be replacedigned null then just check for type replacedignability otherwise allow null.
					if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType (binder.ReturnType) == null)
					{
						condition = Expression.TypeIs (resultMO.Expression, binder.ReturnType);
					}
					else
					{
						condition = Expression.OrElse (
										Expression.Equal (resultMO.Expression, AstUtils.Null),
										Expression.TypeIs (resultMO.Expression, binder.ReturnType));
					}

					Expression checkedConvert = Expression.Condition (
						condition,
						convert,
						Expression.Throw (
							Expression.New (
								InvalidCastException_Ctor_String,
								new TrueReadOnlyCollection<Expression> (
									Expression.Call (
										String_Format_String_ObjectArray,
										Expression.Constant (convertFailed),
										Expression.NewArrayInit (
											typeof (object),
											new TrueReadOnlyCollection<Expression> (
												Expression.Condition (
													Expression.Equal (resultMO.Expression, AstUtils.Null),
													Expression.Constant ("null"),
													Expression.Call (
														resultMO.Expression,
														Object_GetType
													),
													typeof (object)
												)
											)
										)
									)
								)
							),
							binder.ReturnType
						),
						binder.ReturnType
					);

					resultMO = new DynamicMetaObject (checkedConvert, resultMO.Restrictions);
				}

				if (fallbackInvoke != null)
				{
					resultMO = fallbackInvoke (this, binder, resultMO);
				}

				var callDynamic = new DynamicMetaObject (
					Expression.Block (
						new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
						new TrueReadOnlyCollection<Expression> (
							method != DynamicObject_TryBinaryOperation ? Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)) : Expression.replacedign (callArgs, callArgsValue[0]),
							Expression.Condition (
								Expression.Call (
									GetLimitedSelf (),
									method,
									BuildCallArgs (
										binder,
										method.Name == "TryInvokeMember", // JJA
										args,
										callArgs,
										result
									)
								),
								Expression.Block (
									method != DynamicObject_TryBinaryOperation ? ReferenceArgreplacedign (callArgs, args) : AstUtils.Empty,
									resultMO.Expression
								),
								fallbackResult.Expression,
								binder.ReturnType
							)
						)
					),
					GetRestrictions ().Merge (resultMO.Restrictions).Merge (fallbackResult.Restrictions)
				);
				return callDynamic;
			}

19 View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
        {
            /*
               var map = MapFormatterHelper.Deserialize(ref reader,ref context);
               if (map == null)
                   return null;
               context.option.Security.DepthStep(ref reader);
               T t = new T();/new T(map.Count)
               Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
               reader = map.Reader; context = map.Context; 
               reader.Seek(map.EndPos);
               context.Depth--;
               return t;  
            */

            ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
            Type t = typeof(T);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
            //map = MapFormatterHelper.Deserialize(ref reader,ref context);
            ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
            //if (map == null)
            //      goto label;
            ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
            //T t = ctor(map.Count);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
            //MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
            ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));

            //reader = map.Reader; context = map.Context; 
            ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
            //reader.Seek(map.EndPos);
            ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
            //return t;
            ary.Add(Expression.Return(returnTarget, instance));
            //label default(T)
            ary.Add(Expression.Label(returnTarget, instance));

            BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
        }

19 View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari

private Expression GetLimitedSelf ()
			{
				// Convert to GreedyDynamicObject rather than LimitType, because
				// the limit type might be non-public.
				if (TypeUtil.AreEquivalent (Expression.Type, typeof (GreedyDynamicObject)))
				{
					return Expression;
				}
				return Expression.Convert (Expression, typeof (GreedyDynamicObject));
			}

19 View Source File : TrackingExpressionVisitor.cs
License : MIT License
Project Creator : 71

public Expression GenerateBody(Expression body, Expression vsmExpression)
        {
            Debug.replacedert(vsmExpression.Type.IsreplacedignableTo<VirtualStateMachine>());

            if (Variables.Count == 0)
                return body;

            Expression[] loadVariableExpressions = new Expression[Variables.Count];
            Expression[] saveVariableExpressions = new Expression[Variables.Count];

            Expression localsExpression = Expression.Field(vsmExpression, VirtualStateMachine.LocalsField);

            for (int i = 0; i < Variables.Count; i++)
            {
                ParameterExpression variable = Variables[i];

                loadVariableExpressions[i] = Expression.replacedign(
                    variable, Expression.Convert(
                        Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
                        variable.Type
                    )
                );

                saveVariableExpressions[i] = Expression.replacedign(
                    Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
                    Expression.Convert(variable, typeof(object))
                );
            }

            Expression init = loadVariableExpressions.Length == 0
                ? (Expression)Expression.Empty() : Expression.Block(typeof(void), loadVariableExpressions);
            Expression end = saveVariableExpressions.Length == 0
                ? (Expression)Expression.Empty() : Expression.Block(typeof(void), saveVariableExpressions);

            if (body.Type == typeof(void))
                return Expression.Block(Variables, init, body, end);

            ParameterExpression result = Expression.Variable(body.Type, "result");

            return Expression.Block(Variables.Prepend(result), init, Expression.replacedign(result, body), end, result);
        }

19 View Source File : MethodInvoker.cs
License : MIT License
Project Creator : albyho

private static Func<object, object[], object> CreateInvokeDelegate(MethodInfo methodInfo)
        {
            // Target: ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...)

            // parameters to execute
            var instanceParameter = Expression.Parameter(typeof(object), "instance");
            var parametersParameter = Expression.Parameter(typeof(object[]), "parameters");

            // build parameter list
            var parameterExpressions = new List<Expression>();
            var paramInfos = methodInfo.GetParameters();
            for (int i = 0; i < paramInfos.Length; i++)
            {
                // (Ti)parameters[i]
                BinaryExpression valueObj = Expression.ArrayIndex(
                    parametersParameter, Expression.Constant(i));
                UnaryExpression valueCast = Expression.Convert(
                    valueObj, paramInfos[i].ParameterType);

                parameterExpressions.Add(valueCast);
            }

            // non-instance for static method, or ((TInstance)instance)
            var instanceCast = methodInfo.IsStatic ? null :
                Expression.Convert(instanceParameter, methodInfo.ReflectedType);

            // static invoke or ((TInstance)instance).Method
            var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions);

            // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...)
            if (methodCall.Type == typeof(void))
            {
                var lambda = Expression.Lambda<Action<object, object[]>>(
                        methodCall, instanceParameter, parametersParameter);

                Action<object, object[]> execute = lambda.Compile();
                return (instance, parameters) =>
                {
                    execute(instance, parameters);
                    return null;
                };
            }
            else
            {
                var castMethodCall = Expression.Convert(methodCall, typeof(object));
                var lambda = Expression.Lambda<Func<object, object[], object>>(
                    castMethodCall, instanceParameter, parametersParameter);

                return lambda.Compile();
            }
        }

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public static object Deserialize(Type type, ref BssomReader reader, ref BssomDeserializeContext context)
        {
            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(type);

            if (!DeserializerDelegates.TryGetValue(type, out DeserializeMethod deserializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(type);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomReader).MakeByRefType(), "reader");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomDeserializeContext).MakeByRefType(), "context");

                MethodInfo deserializeMethod = formatterType.GetRuntimeMethod(nameof(Deserialize), new[] { typeof(BssomReader).MakeByRefType(), typeof(BssomDeserializeContext).MakeByRefType() });

                //(object)IBssomFormatter<T>.Deserialize(ref reader,option);
                UnaryExpression body = Expression.Convert(Expression.Call(
                    Expression.Convert(param0, formatterType),
                    deserializeMethod,
                    param1,
                    param2), typeof(object));

                deserializerDelegate = Expression.Lambda<DeserializeMethod>(body, param0, param1, param2).Compile();
                DeserializerDelegates.TryAdd(type, deserializerDelegate);
            }

            return deserializerDelegate(formatter, ref reader, ref context);
        }

19 View Source File : FieldAccessor.cs
License : MIT License
Project Creator : albyho

private void InitializeGet(FieldInfo fieldInfo)
        {
            // target: (object)(((TInstance)instance).Field)

            // preparing parameter, object type
            var instance = Expression.Parameter(typeof(object), "instance");

            // non-instance for static method, or ((TInstance)instance)
            var instanceCast = fieldInfo.IsStatic ? null :
                Expression.Convert(instance, fieldInfo.ReflectedType);

            // ((TInstance)instance).Property
            var fieldAccess = Expression.Field(instanceCast, fieldInfo);

            // (object)(((TInstance)instance).Property)
            var castFieldValue = Expression.Convert(fieldAccess, typeof(object));

            // Lambda expression
            var lambda = Expression.Lambda<Func<object, object>>(castFieldValue, instance);

            _getter = lambda.Compile();
        }

19 View Source File : Remute.cs
License : MIT License
Project Creator : ababik

private ParameterResolver[] GetParameterResolvers(Type type, ConstructorInfo constructor)
        {
            var properties = GetInstanceProperties(type);
            var parameters = constructor.GetParameters();

            var parameterResolvers = new ParameterResolver[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];

                var property = FindProperty(type, parameter, properties);

                var parameterExpression = Expression.Parameter(typeof(object));
                var parameterConvertExpression = Expression.Convert(parameterExpression, type);
                var propertyExpression = Expression.Property(parameterConvertExpression, property);
                var propertyConvertExpression = Expression.Convert(propertyExpression, typeof(object));
                var lambdaExpression = Expression.Lambda<Func<object, object>>(propertyConvertExpression, parameterExpression);
                var compiledExpression = lambdaExpression.Compile();

                var parameterResolver = new ParameterResolver(parameter, property, compiledExpression);
                parameterResolvers[i] = parameterResolver;
            }

            return parameterResolvers;
        }

19 View Source File : PropertyAccessor.cs
License : MIT License
Project Creator : albyho

private void InitializeGet(PropertyInfo propertyInfo)
        {
            if (!propertyInfo.CanRead) return;

            // Target: (object)(((TInstance)instance).Property)

            // preparing parameter, object type
            var instance = Expression.Parameter(typeof(object), "instance");

            // non-instance for static method, or ((TInstance)instance)
            var instanceCast = propertyInfo.GetGetMethod(true).IsStatic ? null :
                Expression.Convert(instance, propertyInfo.ReflectedType);

            // ((TInstance)instance).Property
            var propertyAccess = Expression.Property(instanceCast, propertyInfo);

            // (object)(((TInstance)instance).Property)
            var castPropertyValue = Expression.Convert(propertyAccess, typeof(object));

            // Lambda expression
            var lambda = Expression.Lambda<Func<object, object>>(castPropertyValue, instance);

            _getter = lambda.Compile();
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099

static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
        {
            var o_t = typeof(T);
            var o = Expression.Variable(o_t, "o");
            var o_new = Expression.New(typeof(T));

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_try_get_value = d_t.GetMethod("TryGetValue");

            var item_t = typeof(String);
            var item = Expression.Variable(item_t, "item");

            var tc_t = typeof(TypeConverter);
            var tc = Expression.Variable(tc_t, "tc");
            var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
            var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });

            var td_t = typeof(TypeDescriptor);
            var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });

            var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var value_t = x.PropertyType;
                    var value = Expression.Variable(value_t, "value");
                    var target = Expression.Label(x.PropertyType);

                    return Expression.Bind(x, Expression.Block(new[] { item, value },
                        Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
                        Expression.IfThen(
                            Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
                            Expression.IfThen(
                                Expression.NotEqual(item, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
                                    Expression.Block(
                                        Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
                                        Expression.Return(target, value, x.PropertyType))))),
                        Expression.Label(target, value)
                    ));
                }).ToArray();

            var body = Expression.Block(new[] { o, tc },
                Expression.MemberInit(o_new, binds)
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : alelievr

public static bool IsReallyreplacedignableFrom(this Type type, Type otherType)
		{
			if (type.IsreplacedignableFrom(otherType))
				return true;
			if (otherType.IsreplacedignableFrom(type))
				return true;

			try
			{
				var v = Expression.Variable(otherType);
				var expr = Expression.Convert(v, type);
				return expr.Method != null && expr.Method.Name != "op_Implicit";
			}
			catch (InvalidOperationException)
			{
				return false;
			}
		}

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

private static Delegate MakeNullableDeserializer([NotNull] Type nullableType, [NotNull] Type type, [NotNull] Delegate decoder)
		{
			Contract.Requires(nullableType != null && type != null && decoder != null);
			// We have a Decoder of T, but we have to transform it into a Decoder for Nullable<T>, which returns null if the slice is "nil", or falls back to the underlying decoder if the slice contains something

			var prmSlice = Expression.Parameter(typeof(Slice), "slice");
			var body = Expression.Condition(
				// IsNilSegment(slice) ?
				Expression.Call(typeof(FdbTuplePackers).GetMethod("IsNilSegment", BindingFlags.Static | BindingFlags.NonPublic), prmSlice),
				// True => default(Nullable<T>)
				Expression.Default(nullableType),
				// False => decoder(slice)
				Expression.Convert(Expression.Invoke(Expression.Constant(decoder), prmSlice), nullableType)
			);

			return Expression.Lambda(body, prmSlice).Compile();
		}

19 View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma

private object GetValue(MemberExpression member)
        {
            var objectMember = Expression.Convert(member, typeof(object));

            var getterLambda = Expression.Lambda<Func<object>>(objectMember);

            var getter = getterLambda.Compile();

            return getter();
        }

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, object value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                writer.WriteArray1BuildInType(BssomType.Map2);
                BssMapObjMarshal.WriteEmptyMapObject(ref writer);
                return;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SerializerDelegates.TryGetValue(realType, out SerializeMethod serializerDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomWriter).MakeByRefType(), "writer");
                ParameterExpression param2 = Expression.Parameter(typeof(BssomSerializeContext).MakeByRefType(), "context");
                ParameterExpression param3 = Expression.Parameter(typeof(object), "value");

                MethodInfo serializeMethod = formatterType.GetRuntimeMethod(nameof(Serialize), new[] { typeof(BssomWriter).MakeByRefType(), typeof(BssomSerializeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    serializeMethod,
                    param1, param2,
                    realType.IsValueType ? Expression.Unbox(param3, realType) : Expression.Convert(param3, realType)
                    );

                serializerDelegate = Expression.Lambda<SerializeMethod>(body, param0, param1, param2, param3).Compile();
                SerializerDelegates.TryAdd(realType, serializerDelegate);
            }

            serializerDelegate(formatter, ref writer, ref context, value);

        }

19 View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic

Expression BuildContains(JSchema schema, Expression o)
        {
            if (schema.Contains == null)
                return null;

            var val = Expression.Convert(o, typeof(JArray));
            var idx = Expression.Variable(typeof(int));
            var brk = Expression.Label(typeof(bool));
            var len = Expression.Property(val, nameof(JArray.Count));

            return IfThenElseTrue(
                IsTokenType(o, JTokenType.Array),
                Expression.Block(
                    new[] { idx },
                    Expression.replacedign(idx, Expression.Constant(0)),
                    Expression.Loop(
                        Expression.IfThenElse(
                            Expression.Not(Expression.LessThan(idx, len)),
                            Expression.Break(brk, False),
                            Expression.IfThenElse(
                                Eval(schema.Contains, FromItemIndex(val, idx)),
                                Expression.Break(brk, True),
                                Expression.PostIncrementreplacedign(idx))),
                        brk)));
        }

19 View Source File : PropertyObserverNode.cs
License : MIT License
Project Creator : Accelerider

private static Func<T> GetPropertyGetter<T>(object owner, string propertyName)
        {
            var propertyInfo = owner.GetType().GetProperty(propertyName);

            if (propertyInfo == null)
                throw new InvalidOperationException($"No the property named \"{propertyName}\" in the {owner.GetType()} type. ");

            var method = propertyInfo.GetGetMethod();

            return method.ReturnType != typeof(T) && method.ReturnType.IsValueType
                // Warning: Boxes the Value Type.
                ? Lambda<Func<T>>(Convert(Call(Constant(owner), method), typeof(T))).Compile()
                : (Func<T>)Delegate.CreateDelegate(typeof(Func<T>), owner, propertyInfo.GetGetMethod());
        }

19 View Source File : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099

public static void SetPropertyValue(Type sourceType, object source, string propertyOrField, object value)
        {
            if (source == null) return;
            if (sourceType == null) sourceType = source.GetType();
            _dicSetEnreplacedyValueWithPropertyName
                .GetOrAdd(sourceType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyOrField, pf =>
                {
                    var t = sourceType;
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                        Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    var memberInfos = t.GetMember(pf, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.MemberType == MemberTypes.Field || a.MemberType == MemberTypes.Property);
                    foreach (var memberInfo in memberInfos) {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberInfo),
                                Expression.Convert(
                                    parm3,
                                    memberInfo.MemberType == MemberTypes.Field ? (memberInfo as FieldInfo)?.FieldType : (memberInfo as PropertyInfo)?.PropertyType
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                })(source, propertyOrField, value);
        }

19 View Source File : MethodInvoker.cs
License : MIT License
Project Creator : 1100100

private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
            var instanceParameter = Expression.Parameter(typeof(object));
            var argsParameter = Expression.Parameter(typeof(object[]));

            var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));

            var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
            var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
            if (methodCaller.Type == typeof(Task))
            {
                var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
                return (instance, args) => { action(instance, args); return Task.CompletedTask; };
            }

            var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
            return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
        }

19 View Source File : ObjectFormatter.cs
License : MIT License
Project Creator : 1996v

public int Size(ref BssomSizeContext context, object value)
        {
            if (value == null)
            {
                return BssomBinaryPrimitives.NullSize;
            }

            Type realType = value.GetType();
            if (realType == typeof(object))
            {
                return BssMapObjMarshal.Empty.Length + BssomBinaryPrimitives.BuildInTypeCodeSize;
            }

            object formatter = context.Option.FormatterResolver.GetFormatterWithVerify(realType);

            if (!SizeDelegates.TryGetValue(realType, out SizeMethod sizeDelegate))
            {
                Type formatterType = typeof(IBssomFormatter<>).MakeGenericType(realType);
                ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                ParameterExpression param1 = Expression.Parameter(typeof(BssomSizeContext).MakeByRefType(), "context");
                ParameterExpression param2 = Expression.Parameter(typeof(object), "value");

                MethodInfo sizeMethod = formatterType.GetRuntimeMethod(nameof(Size), new[] { typeof(BssomSizeContext).MakeByRefType(), realType });

                MethodCallExpression body = Expression.Call(
                    Expression.Convert(param0, formatterType),
                    sizeMethod, param1,
                    realType.IsValueType ? Expression.Unbox(param2, realType) : Expression.Convert(param2, realType)
                    );

                sizeDelegate = Expression.Lambda<SizeMethod>(body, param0, param1, param2).Compile();
                SizeDelegates.TryAdd(realType, sizeDelegate);
            }

            return sizeDelegate(formatter, ref context, value);
        }

19 View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v

private static Expression BuildDeserializeCore(Type t, ObjectSerializationInfo serializationInfo)
        {
            List<Expression> ary = new List<Expression>();
            LabelTarget returnTarget = Expression.Label(t, "returnLable");
            //int num;
            ParameterExpression num = Expression.Variable(typeof(int), "num");
            //int for-i;
            ParameterExpression forVariable = Expression.Variable(typeof(int), "i");

            //context.option.Security.DepthStep(ref reader);
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);

            //if(reader.TryReadNullWithEnsureBuildInType(BssomType.Array3))
            //      return default(t);
            ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array3),
                Expression.Return(returnTarget, Expression.Default(t))));

            //T t = new T();
            ParameterExpression instance = Expression.Parameter(t, "instance");
            if (serializationInfo.IsDefaultNoArgsCtor)
            {
                ary.Add(Expression.replacedign(instance, Expression.New(t)));
            }
            else
            {
                ParameterInfo[] parInfos = serializationInfo.BestmatchConstructor.GetParameters();
                Expression[] pars = new Expression[parInfos.Length];
                if (serializationInfo.ConstructorParametersIsDefaultValue)
                {
                    for (int i = 0; i < parInfos.Length; i++)
                    {
                        pars[i] = Expression.Default(parInfos[i].ParameterType);
                    }
                    ary.Add(Expression.replacedign(instance, Expression.New(serializationInfo.BestmatchConstructor, pars)));
                }
                else
                {
                    object[] cps = serializationInfo.ConstructorParameters;
                    for (int i = 0; i < parInfos.Length; i++)
                    {
                        pars[i] = Expression.Constant(cps[i], parInfos[i].ParameterType);
                    }
                    ary.Add(Expression.replacedign(instance, Expression.New(serializationInfo.BestmatchConstructor, pars)));
                }
            }

            //reader.SkipVariableNumber()
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);
            //num = reader.ReadVariableNumber()
            ary.Add(Expression.replacedign(num, CommonExpressionMeta.Call_Reader_ReadVariableNumber));
            //i = 0;
            ary.Add(Expression.replacedign(forVariable, Expression.Constant(0)));

            var members = serializationInfo.SerializeMemberInfos;
            if (members.Length > 0)
            {
                //reader.Buffer.Seek(offsetSegment, Current)
                ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Convert(Expression.Multiply(num, Expression.Constant(BssomBinaryPrimitives.FixUInt32NumberSize)), typeof(Int64)), BssomSeekOrgin.Current));
                //switch(i)
                //  case 0: instance.Key0 = readValue();
                //  case 3: instance.Key1 = readValue();
                //  case 5: instance.Key2 = readValue();
                //  default: skipObj();
                FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
                SwitchCase[] switchCases = new SwitchCase[members.Length];
                for (int i = 0; i < members.Length; i++)
                {
                    switchCases[i] = Expression.SwitchCase(SpecialCodeGenExpression.ReadValues(members[i], instance, memFormatters), Expression.Constant(members[i].KeyIndex));
                }
                Expression content = Expression.Switch(
                    typeof(void),
                    forVariable,
                    CommonExpressionMeta.Call_Reader_SkipObject,
                    null,
                    switchCases
                    );

                ary.Add(For(forVariable, Expression.LessThan(forVariable, num), Expression.replacedign(forVariable, Expression.Add(forVariable, Expression.Constant(1))), content));
            }
            //context.Depth--;
            ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);

            ary.Add(Expression.Return(returnTarget, instance));

            ary.Add(Expression.Label(returnTarget, instance));

            return Expression.Block(new ParameterExpression[] { instance, num, forVariable, }, ary);
        }

19 View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71

private Expression ReduceForArray()
		{
			LabelTarget inner_loop_break    = Label("inner_loop_break");
			LabelTarget inner_loop_continue = Label("inner_loop_continue");

			LabelTarget @continue = ContinueLabel ?? Label("continue");
			LabelTarget @break    = BreakLabel ?? Label("break");

			ParameterExpression index = Variable(typeof(int), "i");

			return Block(
				new [] { index, Variable },
                replacedign(index, Constant(0)),
                Loop(
                    Block(
                        IfThen(
                            IsFalse(LessThan(index, ArrayLength(Enumerable))),
                            Break(inner_loop_break)
                        ),
                        replacedign(Variable, Convert(ArrayIndex(Enumerable, index), Variable.Type)),
                        Body,
                        Label(@continue),
                        PreIncrementreplacedign(index)
                    ),
					inner_loop_break,
					inner_loop_continue
                ),
                Label(@break)
            );
		}

19 View Source File : InternalExpressionHelper.cs
License : Apache License 2.0
Project Creator : AKlaus

private static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression methodCallExpression)
        {
            RouteValueDictionary result = new RouteValueDictionary();
            ParameterInfo[] parameters = methodCallExpression.Method.GetParameters();
            if (parameters.Length > 0)
            {
                for (int i = 0; i < parameters.Length; i++)
                {
                    object value;
                    var expressionArgument = methodCallExpression.Arguments[i];
                    if (expressionArgument.NodeType == ExpressionType.Constant)
                    {
                        // If argument is a constant expression, just get the value
                        value = (expressionArgument as ConstantExpression)?.Value ?? string.Empty /* ??? */;
                    }
                    else
                    {
                        try
                        {
                            // Otherwise, convert the argument subexpression to type object,
                            // make a lambda out of it, compile it, and invoke it to get the value
                            var convertExpression = Expression.Convert(expressionArgument, typeof(object));
                            value = Expression.Lambda<Func<object>>(convertExpression).Compile().Invoke();
                        }
                        catch
                        {
                            // ???
                            value = string.Empty;
                        }
                    }
                    result.Add(parameters[i].Name, value);
                }
            }
            return result;
        }

See More Examples