System.Collections.Generic.List.Add(System.Linq.Expressions.Expression)

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

515 Examples 7

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 : 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 : 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 : 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 : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v

private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
        {
            /*
               if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
                    return default;
               context.option.Security.DepthStep(ref reader);
               reader.SkipVariableNumber();
               int len = reader.ReadVariableNumber();
               T t = new T(len);
               Fill<T>(ref t,ref reader,ref context,len);
               context.Depth--;
               return t;  
            */

            bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
            Type t = typeof(T);
            List<Expression> ary = new List<Expression>(7);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");

            if (isArray1Type)
            {
                if (isNativeType)
                {
                    //if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
                else
                {
                    //if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
            }
            else
            {
                //if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
                //      goto label;
                ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
            }

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

            //reader.SkipVariableNumber();
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);

            //int len = reader.ReadVariableNumber();
            ParameterExpression len = Expression.Variable(typeof(int));
            ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));

            //T t = ctor(len);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(len)));
            MethodInfo method = null;
            if (isImplGenerICollec == false)
            {
                //IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
                method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
            }
            else
            {
                if (isArray1Type)
                {
                    //IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
                    method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
                }
                else
                {
                    //IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
                    method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
                }
            }

            ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
            //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[] { instance, len }, ary);
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();


        }

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

private static void GenerateDeserializeWithCore(bool isImplGenerICollec, Type itemType, Func<Expression, Expression> ctor)
        {
            /*
               if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Int8Code))/TryReadNullWithEnsureArray1NativeType(NativeBssomType.CharCode)/TryReadNullWithEnsureBuildInType(BssomType.Array2)
                    return default;
               context.option.Security.DepthStep(ref reader);
               reader.SkipVariableNumber();
               int len = reader.ReadVariableNumber();
               T t = new T(len);
               Fill<T>(ref t,ref reader,ref context,len);
               context.Depth--;
               return t;  
            */

            bool isArray1Type = Array1FormatterHelper.IsArray1Type(itemType, out bool isNativeType, out byte typeCode, out string typeCodeName);
            Type t = typeof(T);
            List<Expression> ary = new List<Expression>(7);
            LabelTarget returnTarget = Expression.Label(t, "returnLable");

            if (isArray1Type)
            {
                if (isNativeType)
                {
                    //if (reader.ryReadNullWithEnsureArray1NativeType(NativeType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1NativeType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
                else
                {
                    //if (reader.Call_Reader_TryReadNullWithEnsureArray1BuildInType(BuildInType))
                    //      goto label;
                    ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureArray1BuildInType(typeCode), Expression.Return(returnTarget, Expression.Default(t))));
                }
            }
            else
            {
                //if (reader.TryReadNullWithEnsureBuildInType(BssomType.Array2))
                //      goto label;
                ary.Add(Expression.IfThen(CommonExpressionMeta.Call_Reader_TryReadNullWithEnsureBuildInType(BssomType.Array2), Expression.Return(returnTarget, Expression.Default(t))));
            }

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

            //reader.SkipVariableNumber();
            ary.Add(CommonExpressionMeta.Call_Reader_SkipVariableNumber);

            //int len = reader.ReadVariableNumber();
            ParameterExpression len = Expression.Variable(typeof(int));
            ary.Add(Expression.replacedign(len, CommonExpressionMeta.Call_Reader_ReadVariableNumber));

            //T t = ctor(len);
            ParameterExpression instance = Expression.Variable(t);
            ary.Add(Expression.replacedign(instance, ctor(len)));
            MethodInfo method = null;
            if (isImplGenerICollec == false)
            {
                //IColloctionFormatterHelper.Fill_ImplIList<T>(ref t,ref reader,ref context,len)
                method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplIList), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
            }
            else
            {
                if (isArray1Type)
                {
                    //IColloctionFormatterHelper.Fill{TypeCodeName}<T>(ref t,ref reader,ref context,len)
                    method = typeof(Array1FormatterHelper).GetMethod(Array1FormatterHelper.FillPrefix + typeCodeName.ToString().Replace("Code", ""), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(t);
                }
                else
                {
                    //IColloctionFormatterHelper.Fill_ImplICollection<T,TElement>(ref t,ref reader,ref context,len)
                    method = typeof(Array2FormatterHelper).GetMethod(nameof(Array2FormatterHelper.Fill_ImplICollection), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(new Type[] { t, itemType });
                }
            }

            ary.Add(Expression.Call(null, method, instance, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext, len));
            //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[] { instance, len }, ary);
            Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();


        }

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

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

            if (!type.IsValueType)
            {
                //if (value==null)
                //     goto label: 1;
                ary.Add(CommonExpressionMeta.Block_IfNullSize(instance, type, returnTarget));
            }

            ParameterExpression size = Expression.Variable(typeof(int));
            SerializeMemberInfo[] mems = serializationInfo.SerializeMemberInfos;
            if (mems.Length == 0)
            {
                ary.Add(Expression.replacedign(size, Expression.Constant(Array3Cache.Empty.Length)));
            }
            else
            {
                int maxLen = mems[mems.Length - 1].KeyIndex + 1;
                ary.Add(Expression.replacedign(size, Expression.Constant(BssomBinaryPrimitives.Array3HeaderSize(maxLen))));

                FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
                int nullNumber = 0;
                int realIndex = 0;
                for (int i = 0; i < maxLen; i++)
                {
                    if (mems[realIndex].KeyIndex != i)
                    {
                        nullNumber++;
                    }
                    else
                    {
                        //Size(mem.Value)
                        ary.Add(SpecialCodeGenExpression.SizeValues(mems[realIndex], instance, size, memFormatters));
                        realIndex++;
                    }
                }
                if (nullNumber > 0)
                    ary.Add(Expression.Addreplacedign(size, Expression.Constant(nullNumber * BssomBinaryPrimitives.NullSize)));
            }

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

            return Expression.Block(new ParameterExpression[] { size }, ary);
        }

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

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

            if (!type.IsValueType)
            {
                //if (value==null)
                //     goto label: 1;
                ary.Add(CommonExpressionMeta.Block_IfNullSize(instance, type, returnTarget));
            }

            ParameterExpression size = Expression.Variable(typeof(int));
            SerializeMemberInfo[] mems = serializationInfo.SerializeMemberInfos;
            if (mems.Length == 0)
            {
                ary.Add(Expression.replacedign(size, Expression.Constant(Array3Cache.Empty.Length)));
            }
            else
            {
                int maxLen = mems[mems.Length - 1].KeyIndex + 1;
                ary.Add(Expression.replacedign(size, Expression.Constant(BssomBinaryPrimitives.Array3HeaderSize(maxLen))));

                FieldInfo memFormatters = serializationInfo.StoreMemberFormatterInstances();
                int nullNumber = 0;
                int realIndex = 0;
                for (int i = 0; i < maxLen; i++)
                {
                    if (mems[realIndex].KeyIndex != i)
                    {
                        nullNumber++;
                    }
                    else
                    {
                        //Size(mem.Value)
                        ary.Add(SpecialCodeGenExpression.SizeValues(mems[realIndex], instance, size, memFormatters));
                        realIndex++;
                    }
                }
                if (nullNumber > 0)
                    ary.Add(Expression.Addreplacedign(size, Expression.Constant(nullNumber * BssomBinaryPrimitives.NullSize)));
            }

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

            return Expression.Block(new ParameterExpression[] { size }, ary);
        }

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

public static void CopyData(Type sourceType, object source, object target)
        {
            if (source == null) return;
            if (target == null) return;
            _copyDataFunc.GetOrAdd(sourceType, type =>
            {
                var sourceParamExp = Expression.Parameter(typeof(object), "sourceObject");
                var targetParamExp = Expression.Parameter(typeof(object), "targetObject");
                var sourceExp = Expression.Variable(type, "source");
                var targetExp = Expression.Variable(type, "target");
                var copyExps = new List<Expression>();
                var sourceFields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                foreach (var field in sourceFields)
                    copyExps.Add(Expression.replacedign(Expression.MakeMemberAccess(targetExp, field), Expression.MakeMemberAccess(sourceExp, field)));

                if (copyExps.Any() == false) return _copyDataFuncEmpty;
                var bodyExp = Expression.Block(
                    new[] {
                            sourceExp, targetExp
                    },
                    new[] {
                            Expression.IfThen(
                                Expression.NotEqual(sourceParamExp, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.NotEqual(targetParamExp, Expression.Constant(null)),
                                    Expression.Block(
                                        Expression.replacedign(sourceExp, Expression.TypeAs(sourceParamExp, sourceType)),
                                        Expression.replacedign(targetExp, Expression.TypeAs(targetParamExp, sourceType)),
                                        Expression.IfThen(
                                            Expression.NotEqual(sourceExp, Expression.Constant(null)),
                                            Expression.IfThen(
                                                Expression.NotEqual(sourceExp, Expression.Constant(null)),
                                                Expression.Block(
                                                    copyExps.ToArray()
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                    }
                );
                return Expression.Lambda<Action<object, object>>(bodyExp, sourceParamExp, targetParamExp).Compile();
            })(source, target);
        }

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 : 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 : ExpressionTree.cs
License : MIT License
Project Creator : 71

public static List<Expression> FindAll(this Expression tree, Predicate<Expression> predicate)
        {
            List<Expression> result = new List<Expression>();
            ExpressionPipeline visitor = Expressive.Pipeline();

            visitor.Pipeline += expr =>
            {
                if (predicate(expr))
                {
                    result.Add(expr);
                    visitor.Stop();
                }

                return expr;
            };

            visitor.Visit(tree);

            return result;
        }

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

protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
        {
            List<Expression> list = null;
            for (int i = 0, n = original.Count; i < n; i++)
            {
                Expression p = Visit(original[i]);
                if (list != null)
                {
                    list.Add(p);
                }
                else if (p != original[i])
                {
                    list = new List<Expression>(n);
                    for (int j = 0; j < i; j++)
                    {
                        list.Add(original[j]);
                    }
                    list.Add(p);
                }
            }
            if (list != null)
            {
                return list.AsReadOnly();
            }
            return original;
        }

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 : 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 : SqlQueryable.cs
License : MIT License
Project Creator : AlenToma

public ISqlQueryable<T> Where(Expression<Predicate<T>> match)
        {
            _matches.Add(match);
            return this;
        }

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

public ISqlQueryable<T> Where(string expression)
        {
            var indicator = expression.Split('.').First();
            var p = Expression.Parameter(typeof(T), indicator);
            var e = Helper.DynamicExpression.ParseLambda(new[] { p }, null, expression);
            _matches.Add(e);
            return this;
        }

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

public ISqlQueryable<T> OrderBy<P>(Expression<Func<T, P>> exp)
        {
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderBy", new Type[] { typeof(T), exp.ReturnType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

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

public ISqlQueryable<T> OrderBy(string columnName)
        {
            var prop = FastDeepCloner.DeepCloner.GetFastDeepClonerProperties(typeof(T)).FirstOrDefault(x => string.Equals(columnName, x.Name, StringComparison.CurrentCultureIgnoreCase));
            if (prop == null)
            {

                throw new EnreplacedyException($"T dose not containe property {columnName}");
            }
            var param = Expression.Parameter(typeof(T));
            var field = Expression.PropertyOrField(param, prop.Name);
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var funcType = typeof(Func<,>).MakeGenericType(typeof(T), prop.PropertyType);
            Expression exp = Expression.Lambda(funcType, field, param);
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderBy", new Type[] { typeof(T), prop.PropertyType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

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

public ISqlQueryable<T> OrderByDescending(string columnName)
        {
            var prop = FastDeepCloner.DeepCloner.GetFastDeepClonerProperties(typeof(T)).FirstOrDefault(x => string.Equals(columnName, x.Name, StringComparison.CurrentCultureIgnoreCase));
            if (prop == null)
            {
                throw new EnreplacedyException($"T dose not containe property {columnName}");
            }
            var param = Expression.Parameter(typeof(T));
            var field = Expression.PropertyOrField(param, prop.Name);
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var funcType = typeof(Func<,>).MakeGenericType(typeof(T), prop.PropertyType);
            Expression exp = Expression.Lambda(funcType, field, param);
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderByDescending", new Type[] { typeof(T), prop.PropertyType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

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

public ISqlQueryable<T> OrderByDescending<P>(Expression<Func<T, P>> exp)
        {
            var list = Expression.Parameter(typeof(IEnumerable<T>), "list");
            var orderByExp = Expression.Call(typeof(Enumerable), "OrderByDescending", new Type[] { typeof(T), exp.ReturnType }, list, exp);
            _matches.Add(orderByExp);
            return this;
        }

19 View Source File : BaseSpecification.cs
License : MIT License
Project Creator : Andyhacool

protected virtual void AddInclude(Expression<Func<T, object>> includeExpression)
        {
            Includes.Add(includeExpression);
        }

19 View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : anthonyreilly

protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
        {
            if (original != null)
            {
                List<Expression> list = null;
                for (int i = 0, n = original.Count; i < n; i++)
                {
                    Expression p = this.Visit(original[i]);
                    if (list != null)
                    {
                        list.Add(p);
                    }
                    else if (p != original[i])
                    {
                        list = new List<Expression>(n);
                        for (int j = 0; j < i; j++)
                        {
                            list.Add(original[j]);
                        }
                        list.Add(p);
                    }
                }
                if (list != null)
                {
                    return list.AsReadOnly();
                }
            }
            return original;
        }

19 View Source File : ExpressionVisitor.cs
License : MIT License
Project Creator : anthonyreilly

protected virtual ReadOnlyCollection<Expression> VisitMemberAndExpressionList(ReadOnlyCollection<MemberInfo> members, ReadOnlyCollection<Expression> original)
        {
            if (original != null)
            {
                List<Expression> list = null;
                for (int i = 0, n = original.Count; i < n; i++)
                {
                    Expression p = this.VisitMemberAndExpression(members != null ? members[i] : null, original[i]);
                    if (list != null)
                    {
                        list.Add(p);
                    }
                    else if (p != original[i])
                    {
                        list = new List<Expression>(n);
                        for (int j = 0; j < i; j++)
                        {
                            list.Add(original[j]);
                        }
                        list.Add(p);
                    }
                }
                if (list != null)
                {
                    return list.AsReadOnly();
                }
            }
            return original;
        }

19 View Source File : SpecificationBuilderExtensions.cs
License : MIT License
Project Creator : ardalis

public static ISpecificationBuilder<T> Where<T>(
            this ISpecificationBuilder<T> specificationBuilder,
            Expression<Func<T, bool>> criteria)
        {
            ((List<Expression<Func<T, bool>>>)specificationBuilder.Specification.WhereExpressions).Add(criteria);

            return specificationBuilder;
        }

19 View Source File : IteratorCompiler.cs
License : MIT License
Project Creator : asc-community

private static Expression CompileNestedLoops(Expression[] shapes, Func<ParameterExpression[], Expression> onIter) 
        {
            var acts = new List<Expression>();

            var locals = new ParameterExpression[shapes.Length];
            for (int i = 0; i < shapes.Length; i++)
                locals[i] = Expression.Parameter(typeof(int), "x_" + i);
            
            var localShapes = new ParameterExpression[shapes.Length];
            for (int i = 0; i < shapes.Length; i++)
                localShapes[i] = Expression.Parameter(typeof(int), "shape_" + i);
            var localShapesreplacedigned = new Expression[shapes.Length];
            for (int i = 0; i < shapes.Length; i++)
                localShapesreplacedigned[i] = Expression.replacedign(localShapes[i], shapes[i]);

            Expression currExpr = onIter(locals);

            for (int i = shapes.Length - 1; i >= 0; i--) {
                currExpr = CreateLoop(locals[i], localShapes[i], currExpr);
            }

            acts.AddRange(localShapesreplacedigned);
            acts.Add(currExpr);

            var localVariables = new List<ParameterExpression>();
            localVariables.AddRange(locals);
            localVariables.AddRange(localShapes);

            return Expression.Block(localVariables, Expression.Block(acts));
        }

19 View Source File : IteratorCompiler.cs
License : MIT License
Project Creator : asc-community

private static Action<GenTensor<T, TWrapper>, GenTensor<T, TWrapper>, GenTensor<T, TWrapper>> CompileForNDimensions(int N, Func<Expression, Expression, Expression> operation, bool parallel)
        {
            var a = Expression.Parameter(typeof(GenTensor<T, TWrapper>), "a");
            var b = Expression.Parameter(typeof(GenTensor<T, TWrapper>), "b");
            var res = Expression.Parameter(typeof(GenTensor<T, TWrapper>), "res");

            var aData = Expression.Parameter(typeof(T[]), "aData");
            var bData = Expression.Parameter(typeof(T[]), "bData");
            var resData = Expression.Parameter(typeof(T[]), "resData");

            var actions = new List<Expression>();

            var (local_aBlocks, actABlocks) = CompileLocalBlocks(a, N, "a");

            // ablocks_0 = a.blocks[0]
            // ablocks_1 = a.blocks[1]
            // ...
            actions.AddRange(actABlocks);

            var (local_bBlocks, actBBlocks) = CompileLocalBlocks(b, N, "b");

            // bblocks_0 = b.blocks[0]
            // bblocks_1 = b.blocks[1]
            // ...
            actions.AddRange(actBBlocks);
            var (local_resBlocks, actResBlocks) = CompileLocalBlocks(res, N, "res");

            // resblocks_0 = res.blocks[0]
            // resblocks_1 = res.blocks[1]
            // ...
            actions.AddRange(actResBlocks);

            var fieldInfo = typeof(GenTensor<T, TWrapper>).GetField(nameof(GenTensor<T, TWrapper>.data));

            // aData = a.data
            actions.Add(Expression.replacedign(aData, Expression.Field(a, fieldInfo)));

            // bData = b.data
            actions.Add(Expression.replacedign(bData, Expression.Field(b, fieldInfo)));

            // resData = res.data
            actions.Add(Expression.replacedign(resData, Expression.Field(res, fieldInfo)));

            var local_ALinOffset = Expression.Parameter(typeof(int), "aLin");

            // aLin = a.LinOffset
            actions.Add(Expression.replacedign(local_ALinOffset, 
                Expression.Field(a, typeof(GenTensor<T, TWrapper>).GetField(nameof(GenTensor<T, TWrapper>.LinOffset)))));

            var local_BLinOffset = Expression.Parameter(typeof(int), "bLin");

            // bLin = b.LinOffset
            actions.Add(Expression.replacedign(local_BLinOffset, 
                Expression.Field(b, typeof(GenTensor<T, TWrapper>).GetField(nameof(GenTensor<T, TWrapper>.LinOffset)))));

            Expression onIter(ParameterExpression[] vars)
            {
                // ablocks_0 * x_0 + ablocks_1 * x_1 + ...
                var aIndex = ExpressionCompiler<T, TWrapper>.BuildIndexToData(vars, local_aBlocks);

                // bblocks_0 * x_0 + bblocks_1 * x_1 + ...
                var bIndex = ExpressionCompiler<T, TWrapper>.BuildIndexToData(vars, local_bBlocks);

                // + aLinOffset
                aIndex = Expression.Add(aIndex, local_ALinOffset);

                // + bLinOffset
                bIndex = Expression.Add(bIndex, local_BLinOffset);

                // a.data
                var aDataField = aData;

                // d.data
                var bDataField = bData;

                // a.data[aIndex]
                var aDataIndex = Expression.ArrayIndex(aDataField, aIndex);

                // b.data[bIndex]
                var bDataIndex = Expression.ArrayIndex(bDataField, bIndex);

                // a.data[aIndex] + b.data[bIndex]
                var added = operation(aDataIndex, bDataIndex);

                // resblocks_0 * x_0 + ...
                var resIndex = ExpressionCompiler<T, TWrapper>.BuildIndexToData(vars, local_resBlocks);

                // res.data
                var resField = resData;

                // res.data[resIndex] = 
                var accessRes = Expression.ArrayAccess(resField, resIndex);

                var replacedign = Expression.replacedign(accessRes, added);

                return replacedign;
            }

            var locals = new List<ParameterExpression>();
            locals.AddRange(local_aBlocks);
            locals.AddRange(local_bBlocks);
            locals.AddRange(local_resBlocks);
            locals.Add(local_ALinOffset);
            locals.Add(local_BLinOffset);
            locals.Add(aData);
            locals.Add(bData);
            locals.Add(resData);

            var shapeInfo = typeof(GenTensor<T, TWrapper>).GetProperty(nameof(GenTensor<T, TWrapper>.Shape));
            var shapeFieldInfo = typeof(TensorShape).GetField(nameof(TensorShape.shape));
            var shapeProperty = Expression.Property(res, shapeInfo);
            var shapeField = Expression.Field(shapeProperty, shapeFieldInfo);

            var loops = ExpressionCompiler<T, TWrapper>.CompileNestedLoops(
                Enumerable.Range(0, N).Select(
                    id =>
                        Expression.ArrayIndex(
                            shapeField,
                            Expression.Constant(id))
                ).ToArray(),
                onIter, parallel, locals.ToArray()
            );

            actions.Add(loops);

            Expression bl = Expression.Block(
                locals, actions.ToArray()
                );

            if (bl.CanReduce)
                bl = bl.Reduce();

            return Expression.Lambda<Action<GenTensor<T, TWrapper>, GenTensor<T, TWrapper>, GenTensor<T, TWrapper>>>(bl, a, b, res).Compile();
        }

19 View Source File : XpressionMapperVisitor.cs
License : MIT License
Project Creator : AutoMapper

protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            var parameterExpression = node.GetParameterExpression();
            if (parameterExpression != null)
                InfoDictionary.Add(parameterExpression, TypeMappings);

            var listOfArgumentsForNewMethod = node.Arguments.Aggregate(new List<Expression>(), (lst, next) =>
            {
                var mappedNext = this.Visit(next);
                TypeMappings.AddTypeMapping(ConfigurationProvider, next.Type, mappedNext.Type);

                lst.Add(mappedNext);
                return lst;
            });//Arguments could be expressions or other objects. e.g. s => s.UserId  or a string "ZZZ".  For extention methods node.Arguments[0] is usually the helper object itself

            //type args are the generic type args e.g. T1 and T2 MethodName<T1, T2>(method arguments);
            var typeArgsForNewMethod = node.Method.IsGenericMethod
                ? node.Method.GetGenericArguments().Select(type => this.TypeMappings.ReplaceType(type)).ToList()//not converting the type it is not in the typeMappings dictionary
                : null;

            ConvertTypesIfNecessary(node.Method.GetParameters(), listOfArgumentsForNewMethod, node.Method);

            return node.Method.IsStatic
                    ? GetStaticExpression()
                    : GetInstanceExpression(this.Visit(node.Object));

            MethodCallExpression GetInstanceExpression(Expression instance)
                => node.Method.IsGenericMethod
                    ? Expression.Call(instance, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
                    : Expression.Call(instance, node.Method, listOfArgumentsForNewMethod.ToArray());

            MethodCallExpression GetStaticExpression()
                => node.Method.IsGenericMethod
                    ? Expression.Call(node.Method.DeclaringType, node.Method.Name, typeArgsForNewMethod.ToArray(), listOfArgumentsForNewMethod.ToArray())
                    : Expression.Call(node.Method, listOfArgumentsForNewMethod.ToArray());
        }

19 View Source File : ProjectionVisitor.cs
License : MIT License
Project Creator : AutoMapper

protected override Expression VisitMemberInit(MemberInitExpression node)
        {
            ODataExpansionOptions expansion = expansions.First();

            if (node.NewExpression.Type != expansion.ParentType)
                return base.VisitMemberInit(node);

            return Expression.MemberInit
            (
                Expression.New(node.Type),
                node.Bindings.OfType<Memberreplacedignment>().Aggregate
                (
                    new List<MemberBinding>(),
                    AddBinding
                )
            );

            List<MemberBinding> AddBinding(List<MemberBinding> list, Memberreplacedignment binding)
            {
                if (ListTypesAreEquivalent(binding.Member.GetMemberType(), expansion.MemberType)
                        && string.Compare(binding.Member.Name, expansion.MemberName, true) == 0)//found the expansion
                {
                    if (foundExpansions.Count > 0)
                        throw new NotSupportedException("Recursive queries not supported");

                    AddBindingExpression(GetBindingExpression(binding, expansion));
                }
                else
                {
                    list.Add(binding);
                }

                return list;

                void AddBindingExpression(Expression bindingExpression)
                {
                    list.Add(Expression.Bind(binding.Member, bindingExpression));
                    foundExpansions.Add(bindingExpression);
                }
            }
        }

19 View Source File : ServerHandler.cs
License : MIT License
Project Creator : azist

private Func<object, RequestMsg, object> getFBody(MethodInfo miContract)
            {
               var attr = miContract.GetCustomAttribute(typeof(ArgsMarshallingAttribute)) as ArgsMarshallingAttribute;
               if (attr==null) return null;

               var tReqMsg = attr.RequestMsgType;

                var pInstance = Expression.Parameter(typeof(object));
                var pMsg = Expression.Parameter(typeof(RequestMsg));
                var pCastMsg = Expression.Variable(tReqMsg);

                var exprArgs = new List<Expression>();
                var pars = miContract.GetParameters();
                for(var i=0; i<pars.Length; i++)
                {
                   var par = pars[i];
                   if (par.ParameterType.IsByRef || par.IsOut || par.ParameterType.IsGenericParameter)
                     throw new ServerContractException(StringConsts.GLUE_METHOD_SPEC_UNSUPPORTED_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, par.Name));

                   var fName = "MethodArg_{0}_{1}".Args(i, par.Name);
                   exprArgs.Add( Expression.Field(pCastMsg, fName) );
                }

               try
               {
                 var isVoid = miContract.ReturnType==typeof(void);

                 if (isVoid)
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                 Expression.Constant(null, typeof(object))
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
                 else
                 {
                     return Expression.Lambda<Func<object, RequestMsg, object>>(
                                        Expression.Block(
                                                 new ParameterExpression[]{pCastMsg},
                                                 Expression.replacedign(pCastMsg, Expression.Convert( pMsg, tReqMsg ) ),
                                                 Expression.Convert(
                                                    Expression.Call( Expression.Convert( pInstance, Contract), miContract, exprArgs.ToArray()),
                                                    typeof(object)
                                                 )
                                         ),//block
                                         pInstance, pMsg)
                                      .Compile();
                 }
               }
               catch(Exception error)
               {
                 throw new ServerContractException(StringConsts.GLUE_METHOD_ARGS_MARSHAL_LAMBDA_ERROR.Args(miContract.DeclaringType.FullName, miContract.Name, error.ToMessageWithType()), error);
               }
            }

19 View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist

private dyn_serialize makeSerialize()
    {
      var _walkArrayWrite = typeof(TypeDescriptor).GetMethod("walkArrayWrite", BindingFlags.NonPublic | BindingFlags.Static);

      var pSchema   = Expression.Parameter(typeof(TypeSchema));
      var pWriter   = Expression.Parameter(typeof(SlimWriter));
      var pTReg     = Expression.Parameter(typeof(TypeRegistry));
      var pRefs     = Expression.Parameter(typeof(RefPool));
      var pInstance = Expression.Parameter(typeof(object));
      var pStreamingContext = Expression.Parameter(typeof(StreamingContext));

      var expressions = new List<Expression>();

      var instance = Expression.Variable(Type, "instance");

      expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));


      if (IsPrimitive)
      {
        expressions.Add(  Expression.Call(pWriter,
                                Format.GetWriteMethodForType(Type),
                                instance) );
      }
      else if (IsArray)
      {
          var elmType = Type.GetElementType();

          if (Format.IsTypeSupported(elmType))//array element type
          {  //spool whole array into writer using primitive types

            var pElement = Expression.Parameter(typeof(object));
            expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pWriter,
                                                                              Format.GetWriteMethodForType(elmType),
                                                                              Expression.Convert(pElement, elmType)), pElement)
                                            )
              );
          }
          else
          {  //spool whole array using TypeSchema because objects may change type
            var pElement = Expression.Parameter(typeof(object));

            if (!elmType.IsValueType)//reference type
              expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pSchema,
                                                                typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
                                                                pWriter,
                                                                pTReg,
                                                                pRefs,
                                                                Expression.Convert( pElement, typeof(object) ),
                                                                pStreamingContext),
                                                                pElement)
                                            )
                            );
            else
              expressions.Add( Expression.Call(_walkArrayWrite,
                                              instance,
                                              Expression.Lambda(Expression.Call(pSchema,
                                                                typeof(TypeSchema).GetMethod("Serialize"),
                                                                pWriter,
                                                                pTReg,
                                                                pRefs,
                                                                pElement,
                                                                pStreamingContext,
                                                                Expression.Constant(elmType)//valueType
                                                                ), pElement)
                                      )
              );
          }
      }
      else
      {
        foreach(var field in Fields)
        {
          Expression expr = null;
          Type t = field.FieldType;

          if (Format.IsTypeSupported(t))
          {
            expr = Expression.Call(pWriter,
                                    Format.GetWriteMethodForType(t),
                                    Expression.Field(instance, field));
          }
          else
          if (t.IsEnum)
          {
            expr = Expression.Call(pWriter,
                                    Format.GetWriteMethodForType(typeof(int)),
                                    Expression.Convert(Expression.Field(instance, field), typeof(int)));

          }
          else // complex type ->  struct or reference
          {
            if (!t.IsValueType)//reference type -> write metahandle
            {
              expr = Expression.Call(pSchema,
                                        typeof(TypeSchema).GetMethod("writeRefMetaHandle"),
                                        pWriter,
                                        pTReg,
                                        pRefs,
                                        Expression.Convert( Expression.Field(instance, field), typeof(object) ),
                                        pStreamingContext);
            }
            else
            expr = Expression.Call(pSchema,
                                    typeof(TypeSchema).GetMethod("Serialize"),
                                    pWriter,
                                    pTReg,
                                    pRefs,
                                    Expression.Convert( Expression.Field(instance, field), typeof(object) ),
                                    pStreamingContext,
                                    Expression.Constant(field.FieldType));//valueType

          }

          expressions.Add(expr);
        }//foreach
        }

      var body = Expression.Block(new ParameterExpression[]{instance}, expressions);

      return Expression.Lambda<dyn_serialize>(body, pSchema, pWriter, pTReg, pRefs, pInstance, pStreamingContext).Compile();
    }

19 View Source File : TypeSchema.cs
License : MIT License
Project Creator : azist

private dyn_deserialize makeDeserialize()
      {
          var pSchema   = Expression.Parameter(typeof(TypeSchema));
          var pReader   = Expression.Parameter(typeof(SlimReader));
          var pTReg     = Expression.Parameter(typeof(TypeRegistry));
          var pRefs     = Expression.Parameter(typeof(RefPool));
          var pInstance = Expression.Parameter(typeof(object).MakeByRefType());
          var pStreamingContext = Expression.Parameter(typeof(StreamingContext));

          var expressions = new List<Expression>();

          var instance = Expression.Variable(Type, "instance");

          expressions.Add( Expression.replacedign(instance, Expression.Convert(pInstance, Type)));


          if (IsPrimitive)
          {
            expressions.Add( Expression.replacedign
                                      (instance,  Expression.Call(pReader, Format.GetReadMethodForType(Type)) )
                            );

          }
          else if (IsArray)
          {
              var elmType = Type.GetElementType();
              var _walkArrayRead = typeof(TypeDescriptor).GetMethod("walkArrayRead", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(elmType);

              if (Format.IsTypeSupported(elmType))//array element type
              {
                //spool whole array from reader using primitive types
                expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(Expression.Call(pReader, Format.GetReadMethodForType(elmType)))
                                                )
                  );
              }
              else
              {  //spool whole array using TypeSchema because objects may change type
                if (!elmType.IsValueType)//reference type
                  expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(
                                                                  Expression.Convert(
                                                                                    Expression.Call(pSchema,
                                                                                                typeof(TypeSchema).GetMethod("readRefMetaHandle"),
                                                                                                pReader,
                                                                                                pTReg,
                                                                                                pRefs,
                                                                                                pStreamingContext),
                                                                                    elmType
                                                                                    )
                                                                  )
                                                )
                                );
                else
                  expressions.Add( Expression.Call(_walkArrayRead,
                                                  instance,
                                                  Expression.Lambda(
                                                                  Expression.Convert(
                                                                                    Expression.Call(pSchema,
                                                                                            typeof(TypeSchema).GetMethod("Deserialize"),
                                                                                            pReader,
                                                                                            pTReg,
                                                                                            pRefs,
                                                                                            pStreamingContext,
                                                                                            Expression.Constant(elmType)),//valueType
                                                                                  elmType
                                                                                  )
                                                                    )
                                                )
                                );
              }
          }
          else//loop through fields
          {
            foreach(var field in Fields)
            {
                      Expression expr = null;
                      Type t = field.FieldType;

                      Expression replacedignmentTargetExpression;
                      if (field.IsInitOnly)//readonly fields must be replacedigned using reflection
                      {
                        replacedignmentTargetExpression =  Expression.Variable(t, "readonlyFieldValue");
                      }
                      else
                        replacedignmentTargetExpression = Expression.Field(instance, field);


                      if (Format.IsTypeSupported(t))
                      {
                        expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Call(pReader, Format.GetReadMethodForType(t))
                                                  );
                      }
                      else
                      if (t.IsEnum)
                      {
                        expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Convert(
                                                          Expression.Call(pReader, Format.GetReadMethodForType(typeof(int))),
                                                          field.FieldType
                                                          )
                                                  );
                      }
                      else // complex type ->  struct or reference
                      {
                        if (!t.IsValueType)//reference type -> read metahandle
                        {
                          expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,

                                                    Expression.Convert(
                                                            Expression.Call(pSchema,
                                                                        typeof(TypeSchema).GetMethod("readRefMetaHandle"),
                                                                        pReader,
                                                                        pTReg,
                                                                        pRefs,
                                                                        pStreamingContext),
                                                        field.FieldType)
                                                    );
                        }
                        else
                        {
                          expr =  Expression.replacedign(
                                                    replacedignmentTargetExpression,
                                                    Expression.Convert(
                                                            Expression.Call(pSchema,
                                                                            typeof(TypeSchema).GetMethod("Deserialize"),
                                                                            pReader,
                                                                            pTReg,
                                                                            pRefs,
                                                                            pStreamingContext,
                                                                            Expression.Constant(field.FieldType)),//valueType
                                                            field.FieldType)
                                                    );
                        }
                      }

                      if (replacedignmentTargetExpression is ParameterExpression)//readonly fields
                      {
                        if (Type.IsValueType)//20150405DKh added
                        {
                          var vBoxed = Expression.Variable(typeof(object), "vBoxed");
                          var box = Expression.replacedign(vBoxed, Expression.TypeAs( instance, typeof(object)));//box the value type
                          var setField =  Expression.Call( Expression.Constant(field),
                                                              typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
                                                              vBoxed, //on boxed struct
                                                              Expression.Convert( replacedignmentTargetExpression, typeof(object))
                                                        );
                          var swap = Expression.replacedign( instance,  Expression.Unbox(vBoxed, Type));
                          expressions.Add(
                              Expression.Block
                              (new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression, vBoxed},
                                box,
                                expr,
                                setField,
                                swap
                              )
                          );
                        }
                        else
                        {

                          var setField =  Expression.Call( Expression.Constant(field),
                                                              typeof(FieldInfo).GetMethod("SetValue", new Type[]{typeof(object), typeof(object)}),
                                                              instance,
                                                              Expression.Convert( replacedignmentTargetExpression, typeof(object))
                                                        );
                          expressions.Add( Expression.Block(new ParameterExpression[]{(ParameterExpression)replacedignmentTargetExpression}, expr, setField) );
                        }
                      }
                      else
                        expressions.Add(expr);
            }//foreach
            }//loop through fields


        expressions.Add( Expression.replacedign(pInstance, Expression.Convert(instance, typeof(object))));

        var body = Expression.Block(new ParameterExpression[]{instance}, expressions);
        return Expression.Lambda<dyn_deserialize>(body, pSchema, pReader, pTReg, pRefs, pInstance, pStreamingContext).Compile();
      }

19 View Source File : ConstantFolding.cs
License : MIT License
Project Creator : Azure

public static ReadOnlyCollection<Expression> FoldExpressionList(ReadOnlyCollection<Expression> inputExpressionList)
        {
            List<Expression> list = null;
            for (int i = 0; i < inputExpressionList.Count; i++)
            {
                Expression p = ConstantFolding.Fold(inputExpressionList[i]);
                if (list != null)
                {
                    list.Add(p);
                }
                else if (p != inputExpressionList[i])
                {
                    list = new List<Expression>(inputExpressionList.Count);
                    for (int j = 0; j < i; j++)
                    {
                        list.Add(inputExpressionList[j]);
                    }
                    list.Add(p);
                }
            }

            if (list != null)
            {
                return list.AsReadOnly();
            }

            return inputExpressionList;
        }

19 View Source File : DefaultMethodInvokerFactory.cs
License : MIT License
Project Creator : Azure

public IMethodInvoker<TInstance, TReturn> Create<TInstance, TReturn>(MethodInfo method)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            if (typeof(TInstance) != method.ReflectedType)
            {
                throw new InvalidOperationException("The Type must match the method's ReflectedType.");
            }

            // Parameter to invoker: TInstance instance
            ParameterExpression instanceParameter = Expression.Parameter(typeof(TInstance), "instance");

            // Parameter to invoker: object[] arguments
            ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");

            // Local variables preplaceded as arguments to Call
            List<ParameterExpression> localVariables = new List<ParameterExpression>();

            // Pre-Call, copy from arguments array to local variables.
            List<Expression> arrayToLocalsreplacedignments = new List<Expression>();

            // Post-Call, copy from local variables back to arguments array.
            List<Expression> localsToArrayreplacedignments = new List<Expression>();

            // If the method returns a value: T returnValue
            ParameterExpression returnValue;

            Type returnType = method.ReturnType;
            if (returnType == typeof(void))
            {
                returnValue = null;
            }
            else
            {
                returnValue = Expression.Parameter(returnType);
            }

            ParameterInfo[] parameterInfos = method.GetParameters();
            Debug.replacedert(parameterInfos != null);

            for (int index = 0; index < parameterInfos.Length; index++)
            {
                ParameterInfo parameterInfo = parameterInfos[index];
                Type argumentType = parameterInfo.ParameterType;

                if (argumentType.IsByRef)
                {
                    // The type of the local variable (and object in the arguments array) should be T rather than T&.
                    argumentType = argumentType.GetElementType()!;
                }

                // T argumentN
                ParameterExpression localVariable = Expression.Parameter(argumentType);
                localVariables.Add(localVariable);

                // arguments[index]
                Expression arrayAccess = Expression.ArrayAccess(argumentsParameter, Expression.Constant(index));

                // Pre-Call:
                // T argumentN = (T)arguments[index];
                Expression arrayAccessAsT = Expression.Convert(arrayAccess, argumentType);
                Expression replacedignArrayToLocal = Expression.replacedign(localVariable, arrayAccessAsT);
                arrayToLocalsreplacedignments.Add(replacedignArrayToLocal);

                // Post-Call:
                // arguments[index] = (object)argumentN;
                Expression localAsObject = Expression.Convert(localVariable, typeof(object));
                Expression replacedignLocalToArray = Expression.replacedign(arrayAccess, localAsObject);
                localsToArrayreplacedignments.Add(replacedignLocalToArray);
            }

            Expression callInstance;

            if (method.IsStatic)
            {
                callInstance = null;
            }
            else
            {
                callInstance = instanceParameter;
            }

            // Instance call:
            // instance.method(param0, param1, ...);
            // Static call:
            // method(param0, param1, ...);
            Expression call = Expression.Call(callInstance, method, localVariables);
            Expression callResult;

            if (returnType == typeof(void))
            {
                callResult = call;
            }
            else
            {
                // T returnValue = method(param0, param1, ...);
                callResult = Expression.replacedign(returnValue, call);
            }

            List<Expression> blockExpressions = new List<Expression>();
            // T0 argument0 = (T0)arguments[0];
            // T1 argument1 = (T1)arguments[1];
            // ...
            blockExpressions.AddRange(arrayToLocalsreplacedignments);
            // Call(argument0, argument1, ...);
            // or
            // T returnValue = Call(param0, param1, ...);
            blockExpressions.Add(callResult);
            // arguments[0] = (object)argument0;
            // arguments[1] = (object)argument1;
            // ...
            blockExpressions.AddRange(localsToArrayreplacedignments);

            if (returnValue != null)
            {
                // return returnValue;
                blockExpressions.Add(returnValue);
            }

            List<ParameterExpression> blockVariables = new List<ParameterExpression>();
            blockVariables.AddRange(localVariables);

            if (returnValue != null)
            {
                blockVariables.Add(returnValue);
            }

            Expression block = Expression.Block(blockVariables, blockExpressions);

            if (call.Type == typeof(void))
            {
                // for: public void Function()
                var lambda = Expression.Lambda<Action<TInstance, object[]>>(
                    block,
                    instanceParameter,
                    argumentsParameter);
                Action<TInstance, object[]> compiled = lambda.Compile();
                return new VoidMethodInvoker<TInstance, TReturn>(compiled);
            }
            else if (call.Type == typeof(Task))
            {
                // for: public Task Function()
                var lambda = Expression.Lambda<Func<TInstance, object[], Task>>(
                    block,
                    instanceParameter,
                    argumentsParameter);
                Func<TInstance, object[], Task> compiled = lambda.Compile();
                return new VoidTaskMethodInvoker<TInstance, TReturn>(compiled);
            }
            else if (typeof(Task).IsreplacedignableFrom(call.Type))
            {
                // for: public Task<TReturn> Function()
                var lambda = Expression.Lambda<Func<TInstance, object[], Task<TReturn>>>(
                    block,
                    instanceParameter,
                    argumentsParameter);
                Func<TInstance, object[], Task<TReturn>> compiled = lambda.Compile();
                return new TaskMethodInvoker<TInstance, TReturn>(compiled);
            }
            else
            {
                // for: public TReturn Function()
                var lambda = Expression.Lambda<Func<TInstance, object[], TReturn>>(
                    block,
                    instanceParameter,
                    argumentsParameter);
                Func<TInstance, object[], TReturn> compiled = lambda.Compile();
                return new MethodInvokerWithReturnValue<TInstance, TReturn>(compiled);
            }
        }

19 View Source File : InvokableFactory.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team

public static Action<object, object[]> CreateStandInCaller(MethodInfo method)
        {
            var parameters = method.GetParameters();
            var argInstance = Expression.Parameter(typeof(object), "instance");
            var argInstanceConverted = Expression.Convert(
                argInstance,
                parameters[0].ParameterType);
            var args = Expression.Parameter(typeof(object[]), "args");

            // Unpack parameters
            var exArgs = new List<Expression>
            {
                argInstanceConverted
            };
            for (var i = 1; i < method.GetParameters().Length; ++i)
            {
                var param = method.GetParameters()[i];
                var arrayElement = Expression.ArrayIndex(
                    args,
                    Expression.Constant(i - 1));
                var arrayElementConverted =
                    Expression.Convert(arrayElement, param.ParameterType);
                exArgs.Add(arrayElementConverted);
            }

            // Standins are always static with the first argument being the instance.
            var exCall = Expression.Call(null, method, exArgs);

            var lambda =
                Expression.Lambda<Action<object, object[]>>(exCall, argInstance, args);
            return lambda.Compile();
        }

19 View Source File : InvokableFactory.cs
License : MIT License
Project Creator : Bannerlord-Coop-Team

public static Action<object[]> CreateStaticStandInCaller(MethodInfo method)
        {
            var args = Expression.Parameter(typeof(object[]), "args");

            // Unpack parameters
            var exArgs = new List<Expression>();
            for (var i = 0; i < method.GetParameters().Length; ++i)
            {
                var param = method.GetParameters()[i];
                var arrayElement = Expression.ArrayIndex(args, Expression.Constant(i));
                var arrayElementConverted =
                    Expression.Convert(arrayElement, param.ParameterType);
                exArgs.Add(arrayElementConverted);
            }

            // Standins are always static with the first argument being the instance.
            var exCall = Expression.Call(null, method, exArgs);

            var lambda = Expression.Lambda<Action<object[]>>(exCall, args);
            return lambda.Compile();
        }

19 View Source File : ExpressionCompiler.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax

public static Expression OptimizeExpression(ReadOnlyExpressionContext context)
        {
            Expression expression = context.Expression;
            if (context.ScopedExpressions.Count > 1)
            {
                var body = new List<Expression>();
                var variables = new List<ParameterExpression>();
                foreach (IGrouping<Type, MethodCallExpression> grouping in context.ScopedExpressions.GroupBy(x => x.Type))
                {
                    if (grouping.Count() > 1)
                    {
                        MethodCallExpression methodCallExpression = grouping.First();

                        ParameterExpression newValue = Expression.Variable(methodCallExpression.Type);
                        variables.Add(newValue);
                        var visitor = new ScopedExpressionVisitor(methodCallExpression, newValue);
                        expression = visitor.Visit(expression);
                        body.Add(newValue);
                        body.Add(Expression.replacedign(newValue, methodCallExpression));
                    }
                }

                if (body.Count > 0)
                {
                    expression = Expression.Block(variables, body.Concat(new[] { expression }));
                }
            }
            return expression;
        }

19 View Source File : ExpressionGenerator.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax

public ReadOnlyExpressionContext ApplyDecorators(Type serviceType, ServiceBinding serviceBinding, InstanceFactory[] children, Expression[] decorators, Scoped containerScope)
        {
            ExpressionContext context = (ExpressionContext)(serviceBinding.BaseExpression ?? throw new ArgumentNullException($"{nameof(serviceBinding)}.{nameof(serviceBinding.BaseExpression)}"));
            if (decorators.Length > 0)
            {
                var body = new List<Expression>();
                ParameterExpression instanceParameter = Expression.Variable(serviceType, $"{serviceType} instance");
                body.Add(Expression.replacedign(instanceParameter, Expression.Convert(context.Expression, serviceType)));

                var decoratorExpressionVisitor = new DecoratorExpressionVisitor(children, instanceParameter.Type);
                decoratorExpressionVisitor.PreviousDecorator = instanceParameter;
                foreach (Expression decorator in decorators)
                {
                    Expression decoratorExpression = decorator;

                    decoratorExpression = decoratorExpressionVisitor.Visit(decoratorExpression);

                    decoratorExpressionVisitor.PreviousDecorator = decoratorExpression;
                }

                body.Add(decoratorExpressionVisitor.PreviousDecorator);

                if (body.Last().Type == typeof(void)) body.Add(instanceParameter);
                context.Expression = body.Count == 1 ? context.Expression : Expression.Block(new[] { instanceParameter }, body);
                serviceBinding.Lifetime.ApplyLifetimeOnExpression(containerScope, context);
            }

            return context;
        }

19 View Source File : ExpressionGenerator.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax

public ReadOnlyExpressionContext ApplyDecorators(Type serviceType, ServiceBinding serviceBinding, InstanceFactory[] children, Expression[] decorators, Scoped containerScope)
        {
            ExpressionContext context = (ExpressionContext)(serviceBinding.BaseExpression ?? throw new ArgumentNullException($"{nameof(serviceBinding)}.{nameof(serviceBinding.BaseExpression)}"));
            if (decorators.Length > 0)
            {
                var body = new List<Expression>();
                ParameterExpression instanceParameter = Expression.Variable(serviceType, $"{serviceType} instance");
                body.Add(Expression.replacedign(instanceParameter, Expression.Convert(context.Expression, serviceType)));

                var decoratorExpressionVisitor = new DecoratorExpressionVisitor(children, instanceParameter.Type);
                decoratorExpressionVisitor.PreviousDecorator = instanceParameter;
                foreach (Expression decorator in decorators)
                {
                    Expression decoratorExpression = decorator;

                    decoratorExpression = decoratorExpressionVisitor.Visit(decoratorExpression);

                    decoratorExpressionVisitor.PreviousDecorator = decoratorExpression;
                }

                body.Add(decoratorExpressionVisitor.PreviousDecorator);

                if (body.Last().Type == typeof(void)) body.Add(instanceParameter);
                context.Expression = body.Count == 1 ? context.Expression : Expression.Block(new[] { instanceParameter }, body);
                serviceBinding.Lifetime.ApplyLifetimeOnExpression(containerScope, context);
            }

            return context;
        }

19 View Source File : Container.cs
License : GNU Lesser General Public License v3.0
Project Creator : Barsonax

private Action<Scoped, object> GenerateLateInjector(Type type)
        {
            if (Registrations.LateInjectorBindings.TryGetValue(type, out ArrayList<LateInjectorBinding> lateInjectorBindings))
            {
                ParameterExpression instanceParameter = Expression.Parameter(typeof(object));

                var body = new List<Expression>();

                Expression instanceCasted = Expression.Convert(instanceParameter, type);
                foreach (MethodInfo methodInfo in lateInjectorBindings.Array.SelectMany(x => x.InjectionMethods.Array))
                {
                    ParameterInfo[] parameterTypes = methodInfo.GetParameters();
                    var parameterExpressions = new Expression[parameterTypes.Length];
                    for (var i = 0; i < parameterTypes.Length; i++)
                    {
                        Type parameterType = parameterTypes[i].ParameterType;
                        parameterExpressions[i] = DependencyGraph.Resolve(parameterType).Context.Expression;
                    }
                    body.Add(Expression.Call(instanceCasted, methodInfo, parameterExpressions));
                }

                foreach (MemberInfo memberInfo in lateInjectorBindings.Array.SelectMany(x => x.InjectionProperties.Array))
                {
                    MemberExpression memberAccessExpression = Expression.MakeMemberAccess(instanceCasted, memberInfo);
                    body.Add(Expression.replacedign(memberAccessExpression, DependencyGraph.Resolve(memberAccessExpression.Type).Context.Expression));
                }

                if (body.Count == 0) return (scope, instance) => { };
                Expression expression = body.Count == 1 ? body[0] : Expression.Block(body);
                Expression<Action<Scoped, object>> expressionTree = Expression.Lambda<Action<Scoped, object>>(expression, ExpressionGenerator.ScopeParameter, instanceParameter);

                Action<Scoped, object> action = expressionTree.Compile();

                return action;
            }
            else if (_parentContainer != null)
            {
                return _parentContainer.GenerateLateInjector(type);
            }

            return (scope, instance) => { };
        }

19 View Source File : ExpressionRewriter.Switch.cs
License : MIT License
Project Creator : benjamin-hodgson

private static void GetChildren(Span<Expression> children, SwitchExpression s)
        {
            IEnumerable<Expression> GetSwitchCaseChildren(SwitchCase switchCase)
            {
                var list = new List<Expression>(switchCase.TestValues.Count + 1);
                list.AddRange(switchCase.TestValues);
                list.Add(switchCase.Body);
                return list;
            }
            
            children[0] = s.SwitchValue;
            Copy(s.Cases.SelectMany(GetSwitchCaseChildren), children.Slice(1));
        }

19 View Source File : AutoRewriter.cs
License : MIT License
Project Creator : benjamin-hodgson

private Func<T, int> MkCounter(Type nodeType)
        {
            var ctorParams = GetBestConstructor(nodeType)
                ?.GetParameters()
                ?? Enumerable.Empty<ParameterInfo>();  // if no public constructor, replacedume node has no children

            // (children, param) =>
            // {
            //     NodeType node = (NodeType)param;
            //     int count = 0;
            //     IEnumerator<T> enumerator;
            //
            //     // ...
            // 
            // }

            var nodeParam = Expression.Parameter(_t, "param");
            var nodeLocal = Expression.Parameter(nodeType, "node");
            var countLocal = Expression.Parameter(_int, "count");
            var stmts = new List<Expression>
            {
                Expression.replacedign(nodeLocal, Expression.Convert(nodeParam, nodeType)),
            };

            foreach (var ctorParam in ctorParams)
            {
                if (ctorParam.ParameterType.Equals(_t))
                {
                    // i++;
                    var property = nodeType.GetProperty(ParamNameToPropName(ctorParam.Name!));
                    stmts.Add(Expression.replacedign(countLocal, Expression.Increment(countLocal)));
                }
                else if (ImplementsIEnumerableT(ctorParam.ParameterType))
                {
                    // i += Enumerable.Count(node.Children);

                    var property = nodeType.GetProperty(ParamNameToPropName(ctorParam.Name!));
                    var enumerable = Expression.Property(nodeLocal, property);
                    stmts.Add(Expression.Addreplacedign(countLocal, Expression.Call(_enumerable_Count, enumerable)));
                }
                else
                {
                    // the property isn't a T or an IEnumerable<T>, skip it
                }
            }

            stmts.Add(countLocal);

            var body = Expression.Block(new[]{ nodeLocal, countLocal }, stmts);
            var lam = Expression.Lambda<Func<T, int>>(body, $"CountChildren_{_t.Name}_{nodeType.Name}", new[] { nodeParam });
            return lam.Compile();
        }

19 View Source File : AutoRewriter.cs
License : MIT License
Project Creator : benjamin-hodgson

private SpanAction<T, T> MkGetter(Type nodeType)
        {
            var ctorParams = GetBestConstructor(nodeType)
                ?.GetParameters()
                ?? Enumerable.Empty<ParameterInfo>();  // if no public constructor, replacedume node has no children

            // (children, param) =>
            // {
            //     NodeType node = (NodeType)param;
            //     int i = 0;
            //     IEnumerator<T> enumerator;
            //
            //     // ...
            // 
            // }

            var childrenParam = Expression.Parameter(_spanT, "children");
            var nodeParam = Expression.Parameter(_t, "param");
            var nodeLocal = Expression.Parameter(nodeType, "node");
            var indexLocal = Expression.Parameter(_int, "i");
            var enumeratorLocal = Expression.Parameter(_iEnumeratorT, "enumerator");
            var stmts = new List<Expression>
            {
                Expression.replacedign(nodeLocal, Expression.Convert(nodeParam, nodeType)),
            };

            foreach (var ctorParam in ctorParams)
            {
                if (ctorParam.ParameterType.Equals(_t))
                {
                    // children[i] = node.Child;
                    // i++;
                    var property = nodeType.GetProperty(ParamNameToPropName(ctorParam.Name!));
                    stmts.Add(Expression.Call(_replacedignSpanElement, childrenParam, indexLocal, Expression.Property(nodeLocal, property)));
                    stmts.Add(Expression.replacedign(indexLocal, Expression.Increment(indexLocal)));
                }
                else if (ImplementsIEnumerableT(ctorParam.ParameterType))
                {
                    // enumerator = node.Children.GetEnumerator();
                    // while(true)
                    // {
                    //     if (enumerator.MoveNext())
                    //     {
                    //         children[i] = enumerator.Current;
                    //         i++;
                    //     }
                    //     else
                    //     {
                    //         break;
                    //     }
                    // }

                    var property = nodeType.GetProperty(ParamNameToPropName(ctorParam.Name!));
                    var enumerable = Expression.Property(nodeLocal, property);
                    stmts.Add(Expression.replacedign(enumeratorLocal, Expression.Call(enumerable, _iEnumerable_GetEnumerator)));
                    
                    var breakLbl = Expression.Label();
                    var loopBody = Expression.IfThenElse(
                        Expression.Call(enumeratorLocal, _iEnumerator_MoveNext),
                        Expression.Block(
                            Expression.Call(_replacedignSpanElement, childrenParam, indexLocal, Expression.Property(enumeratorLocal, _iEnumeratorT_Current)),
                            Expression.replacedign(indexLocal, Expression.Increment(indexLocal))
                        ),
                        Expression.Goto(breakLbl)
                    );
                    stmts.Add(Expression.Loop(loopBody, breakLbl));
                }
                else
                {
                    // the property isn't a T or an IEnumerable<T>, skip it
                }
            }

            var body = Expression.Block(new[]{ nodeLocal, indexLocal, enumeratorLocal }, stmts);
            var lam = Expression.Lambda<SpanAction<T, T>>(body, $"GetChildren_{_t.Name}_{nodeType.Name}", new[] { childrenParam, nodeParam });
            return lam.Compile();
        }

19 View Source File : AutoRewriter.cs
License : MIT License
Project Creator : benjamin-hodgson

private ReadOnlySpanFunc<T, T, T> MkSetter(Type nodeType)
        {
            var ctor = GetBestConstructor(nodeType);
            var ctorParams = ctor?.GetParameters();

            if (ctorParams == null)
            {
                // if no public constructor, replacedume node has no children, so no rebuilding required
                return (children, x) => x;
            }

            var numberOfDirectChildren = ctorParams.Count(p => p.ParameterType.Equals(_t));
            var enumerablesOfChildren = ctorParams
                .Where(p => ImplementsIEnumerableT(p.ParameterType))
                .Select(p => p.ParameterType)
                .ToList();

            var childrenParam = Expression.Parameter(_readOnlySpanT, "children");
            var nodeParam = Expression.Parameter(_t, "param");
            var nodeLocal = Expression.Parameter(nodeType, "node");
            var retLocal = Expression.Parameter(nodeType, "ret");


            // (children, param) =>
            // {
            //     NodeType param = (NodeType)param;
            //     T ret;
            // 
            //     T child0;
            //     T[] child1;
            //     // etc
            //
            //  
            //     child0 = children[0];
            //     children = children.Slice(1);
            //     
            //     child1 = AutoRewriter.RebuildArray(node.Children1, children);
            //     children = children.Slice(Enumerable.Count(child1));
            //     // etc
            //
            //     ret = new NodeType(node.Foo, child0, child1, node.Bar, child2);
            //     return ret;
            // }
            var childrenInfos = ctorParams
                .Where(p => p.ParameterType.Equals(_t) || ImplementsIEnumerableT(p.ParameterType))
                .Select((param, i) => (local: Expression.Parameter(param.ParameterType, $"child{i}"), param))
                .ToList();
            var childrenLocals = childrenInfos.Select(x => x.local).ToList();

            var stmts = new List<Expression>
            {
                Expression.replacedign(nodeLocal, Expression.Convert(nodeParam, nodeType)),
            };

            stmts.AddRange(
                childrenInfos.SelectMany(x =>
                    x.param.ParameterType.Equals(_t)
                        ? new Expression[]
                        {
                            Expression.replacedign(x.local, Expression.Call(_getReadOnlySpanElement, childrenParam, Expression.Constant(0))),
                            Expression.replacedign(childrenParam, Expression.Call(childrenParam, _readOnlySpanT_Slice, Expression.Constant(1)))
                        }
                        : new Expression[]
                        {
                            Expression.replacedign(
                                x.local,
                                Expression.Call(
                                    _enumerableRebuilders[x.param.ParameterType],
                                    Expression.Property(nodeLocal, nodeType.GetProperty(ParamNameToPropName(x.param.Name!))),
                                    childrenParam
                                )
                            ),
                            Expression.replacedign(childrenParam, Expression.Call(childrenParam, _readOnlySpanT_Slice, Expression.Call(_enumerable_Count, x.local)))
                        }
                )
            );
            stmts.Add(Expression.replacedign(retLocal, CallNodeCtor(ctor!, nodeLocal, childrenLocals.Cast<Expression>().ToList(), nodeType)));
            stmts.Add(retLocal);

            var block = Expression.Block(
                new[]{ nodeLocal, retLocal }.Concat(childrenLocals),
                stmts
            );

            var lam = Expression.Lambda<ReadOnlySpanFunc<T, T, T>>(block, $"SetChildren_{_t.Name}_{nodeType.Name}", new[] { childrenParam, nodeParam });
            return lam.Compile();
        }

19 View Source File : AutoRewriter.cs
License : MIT License
Project Creator : benjamin-hodgson

private static IEnumerable<Expression> NodeCtorArgs(ParameterExpression nodeParam, IEnumerable<ParameterInfo> ctorParams, IList<Expression> childrenExprs, Type nodeType)
        {
            var numberOfTs = 0;
            var args = new List<Expression>(ctorParams.Count());
            foreach (var param in ctorParams)
            {
                if (param.ParameterType.Equals(_t) || ImplementsIEnumerableT(param.ParameterType))
                {
                    args.Add(childrenExprs[numberOfTs]);
                    numberOfTs++;
                }
                else
                {
                    args.Add(AccessNodeProperty(nodeParam, nodeType, param));
                }
            }
            return args;
        }

19 View Source File : HubMethodDispatcher.cs
License : GNU General Public License v3.0
Project Creator : bonarr

private static HubMethodExecutor GetExecutor(MethodInfo methodInfo)
        {
            // Parameters to executor
            ParameterExpression hubParameter = Expression.Parameter(typeof(IHub), "hub");
            ParameterExpression parametersParameter = Expression.Parameter(typeof(object[]), "parameters");

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

                // valueCast is "(Ti) parameters[i]"
                parameters.Add(valueCast);
            }

            // Call method
            UnaryExpression instanceCast = (!methodInfo.IsStatic) ? Expression.Convert(hubParameter, methodInfo.ReflectedType) : null;
            MethodCallExpression methodCall = Expression.Call(instanceCast, methodInfo, parameters);

            // methodCall is "((TController) hub) method((T0) parameters[0], (T1) parameters[1], ...)"
            // Create function
            if (methodCall.Type == typeof(void))
            {
                Expression<VoidHubMethodExecutor> lambda = Expression.Lambda<VoidHubMethodExecutor>(methodCall, hubParameter, parametersParameter);
                VoidHubMethodExecutor voidExecutor = lambda.Compile();
                return WrapVoidAction(voidExecutor);
            }
            else
            {
                // must coerce methodCall to match HubMethodExecutor signature
                UnaryExpression castMethodCall = Expression.Convert(methodCall, typeof(object));
                Expression<HubMethodExecutor> lambda = Expression.Lambda<HubMethodExecutor>(castMethodCall, hubParameter, parametersParameter);
                return lambda.Compile();
            }
        }

19 View Source File : MessageParser.cs
License : MIT License
Project Creator : bonsai-rx

internal static Expression Content(string typeTag, Expression reader)
        {
            if (string.IsNullOrEmpty(typeTag))
            {
                throw new ArgumentException("A valid type tag must be specified.", nameof(typeTag));
            }

            var stack = new Stack<List<Expression>>();
            var arguments = new List<Expression>();
            foreach (var tag in typeTag)
            {
                switch (tag)
                {
                    case TypeTag.Char:
                        arguments.Add(Expression.Call(typeof(MessageParser), nameof(ReadChar), null, reader));
                        break;
                    case TypeTag.TimeTag:
                        arguments.Add(Expression.Call(typeof(MessageParser), nameof(ReadTimeTag), null, reader));
                        break;
                    case TypeTag.Int64: arguments.Add(Expression.Call(reader, ReadInt64)); break;
                    case TypeTag.Int32: arguments.Add(Expression.Call(reader, ReadInt32)); break;
                    case TypeTag.Float: arguments.Add(Expression.Call(reader, ReadFloat)); break;
                    case TypeTag.Double: arguments.Add(Expression.Call(reader, ReadDouble)); break;
                    case TypeTag.Alternate:
                    case TypeTag.String: arguments.Add(Address(reader)); break;
                    case TypeTag.Blob:
                        var blobSize = Expression.Call(reader, ReadInt32);
                        arguments.Add(Expression.Call(typeof(MessageParser), nameof(ReadBlob), null, reader, blobSize));
                        break;
                    case TypeTag.ArrayBegin:
                        stack.Push(arguments);
                        arguments = new List<Expression>();
                        break;
                    case TypeTag.ArrayEnd:
                        var array = Arguments(arguments);
                        if (stack.Count == 0) throw new ArgumentException("Invalid OSC array declaration.", nameof(typeTag));
                        arguments = stack.Pop();
                        arguments.Add(array);
                        break;
                    default: throw new ArgumentException(string.Format("The type tag '{0}' is not supported.", tag), nameof(typeTag));
                }
            };

            if (stack.Count > 0)
            {
                throw new ArgumentException("Unexpected end of type tag. Check for missing array declaration brackets.", nameof(typeTag));
            }
            return Arguments(arguments);
        }

19 View Source File : BatchUtil.cs
License : MIT License
Project Creator : borisdj

public static bool TryCreateUpdateBodyNestedQuery(BatchUpdateCreateBodyData createBodyData, Expression expression, Memberreplacedignment memberreplacedignment)
        {
            if (expression is MemberExpression rootMemberExpression && rootMemberExpression.Expression is ParameterExpression)
            {
                // This is a basic replacedignment expression so don't try checking for a nested query
                return false;
            }

            var rootTypeTableInfo = createBodyData.GetTableInfoForType(createBodyData.RootType);

            var expressionStack = new Stack<ExpressionNode>();
            var visited = new HashSet<Expression>();

            var rootParameterExpressionNodes = new List<ExpressionNode>();
            expressionStack.Push(new ExpressionNode(expression, null));

            // Perform a depth first traversal of the expression tree and see if there is a
            // leaf node in the format rootLambdaParameter.NavigationProperty indicating a nested
            // query is needed
            while (expressionStack.Count > 0)
            {
                var currentExpressionNode = expressionStack.Pop();
                var currentExpression = currentExpressionNode.Expression;
                if (visited.Contains(currentExpression))
                {
                    continue;
                }

                visited.Add(currentExpression);
                switch (currentExpression)
                {
                    case MemberExpression currentMemberExpression:
                        if (currentMemberExpression.Expression is ParameterExpression finalExpression
                            && finalExpression.Name == createBodyData.RootInstanceParameterName)
                        {
                            if (rootTypeTableInfo.AllNavigationsDictionary.TryGetValue(currentMemberExpression.Member.Name, out _))
                            {
                                rootParameterExpressionNodes.Add(new ExpressionNode(finalExpression, currentExpressionNode));
                                break;
                            }
                        }

                        expressionStack.Push(new ExpressionNode(currentMemberExpression.Expression, currentExpressionNode));
                        break;

                    case MethodCallExpression currentMethodCallExpresion:
                        if (currentMethodCallExpresion.Object != null)
                        {
                            expressionStack.Push(new ExpressionNode(currentMethodCallExpresion.Object, currentExpressionNode));
                        }

                        if (currentMethodCallExpresion.Arguments?.Count > 0)
                        {
                            foreach (var argumentExpression in currentMethodCallExpresion.Arguments)
                            {
                                expressionStack.Push(new ExpressionNode(argumentExpression, currentExpressionNode));
                            }
                        }
                        break;

                    case LambdaExpression currentLambdaExpression:
                        expressionStack.Push(new ExpressionNode(currentLambdaExpression.Body, currentExpressionNode));
                        break;

                    case UnaryExpression currentUnaryExpression:
                        expressionStack.Push(new ExpressionNode(currentUnaryExpression.Operand, currentExpressionNode));
                        break;

                    case BinaryExpression currentBinaryExpression:
                        expressionStack.Push(new ExpressionNode(currentBinaryExpression.Left, currentExpressionNode));
                        expressionStack.Push(new ExpressionNode(currentBinaryExpression.Right, currentExpressionNode));
                        break;

                    case ConditionalExpression currentConditionalExpression:
                        expressionStack.Push(new ExpressionNode(currentConditionalExpression.Test, currentExpressionNode));
                        expressionStack.Push(new ExpressionNode(currentConditionalExpression.IfTrue, currentExpressionNode));
                        expressionStack.Push(new ExpressionNode(currentConditionalExpression.IfFalse, currentExpressionNode));
                        break;

                    default:
                        break;
                }
            }

            if (rootParameterExpressionNodes.Count < 1)
            {
                return false;
            }

            if (!(memberreplacedignment.Member is PropertyInfo memberPropertyInfo))
            {
                return false;
            }

            var originalParameterNode = rootParameterExpressionNodes.FirstOrDefault();
            var firstNavigationNode = originalParameterNode.Parent;
            var firstMemberExpression = (MemberExpression)firstNavigationNode.Expression;
            var firstNavigation = rootTypeTableInfo.AllNavigationsDictionary[firstMemberExpression.Member.Name];
            var isFirstNavigationACollectionType = firstNavigation.IsCollection;

            var firstNavigationTargetType = firstNavigation.TargetEnreplacedyType;
            var firstNavigationType = firstNavigationTargetType.ClrType;
            var firstNavigationTableName = firstNavigationTargetType.GetTableName();

            IQueryable innerQueryable;
            if (isFirstNavigationACollectionType)
            {
                var dbSetGenericMethod = DbContextSetMethodInfo.MakeGenericMethod(createBodyData.RootType);
                var dbSetQueryable = (IQueryable)dbSetGenericMethod.Invoke(createBodyData.DbContext, null);

                var rootParameter = originalParameterNode.Expression as ParameterExpression;
                innerQueryable = dbSetQueryable.Provider.CreateQuery(Expression.Call(
                    null,
                    QueryableMethods.Select.MakeGenericMethod(createBodyData.RootType, memberPropertyInfo.PropertyType),
                    dbSetQueryable.Expression,
                    Expression.Lambda(expression, rootParameter)
                ));
            }
            else
            {
                var dbSetGenericMethod = DbContextSetMethodInfo.MakeGenericMethod(firstNavigationType);
                var dbSetQueryable = (IQueryable)dbSetGenericMethod.Invoke(createBodyData.DbContext, null);

                var rootParamterName = $"x{firstMemberExpression.Member.Name}";
                var rootParameter = Expression.Parameter(firstNavigationType, rootParamterName);

                Expression lambdaBody = rootParameter;
                var previousNode = firstNavigationNode;
                var currentNode = previousNode.Parent;
                while (currentNode != null)
                {
                    var wasNodeHandled = false;
                    switch (currentNode.Expression)
                    {
                        case MemberExpression currentMemberExpression:
                            lambdaBody = Expression.MakeMemberAccess(lambdaBody, currentMemberExpression.Member);
                            wasNodeHandled = true;
                            break;

                        case MethodCallExpression currentMethodCallExpression:
                            if (currentMethodCallExpression.Object == previousNode.Expression)
                            {
                                lambdaBody = Expression.Call(lambdaBody, currentMethodCallExpression.Method, currentMethodCallExpression.Arguments);
                                wasNodeHandled = true;
                            }
                            else if (currentMethodCallExpression.Arguments != null)
                            {
                                var didFindArgumentToSwap = false;
                                var newArguments = new List<Expression>();
                                foreach (var nextArgument in currentMethodCallExpression.Arguments)
                                {
                                    if (nextArgument == previousNode.Expression)
                                    {
                                        newArguments.Add(lambdaBody);
                                        didFindArgumentToSwap = true;
                                        continue;
                                    }

                                    newArguments.Add(nextArgument);
                                }

                                if (didFindArgumentToSwap)
                                {
                                    lambdaBody = Expression.Call(currentMethodCallExpression.Object, currentMethodCallExpression.Method, newArguments);
                                    wasNodeHandled = true;
                                }
                            }
                            break;

                        case UnaryExpression currentUnaryExpression:
                            if (currentUnaryExpression.Operand == previousNode.Expression)
                            {
                                lambdaBody = Expression.MakeUnary(currentUnaryExpression.NodeType, lambdaBody, currentUnaryExpression.Type);
                                wasNodeHandled = true;
                            }
                            break;

                        case BinaryExpression currentBinaryExpression:
                            if (currentBinaryExpression.Left == previousNode.Expression)
                            {
                                lambdaBody = Expression.MakeBinary(currentBinaryExpression.NodeType, lambdaBody, currentBinaryExpression.Right);
                                wasNodeHandled = true;
                            }
                            else if (currentBinaryExpression.Right == previousNode.Expression)
                            {
                                lambdaBody = Expression.MakeBinary(currentBinaryExpression.NodeType, currentBinaryExpression.Left, lambdaBody);
                                wasNodeHandled = true;
                            }
                            break;

                        case LambdaExpression currentLambdaExpression:
                            if (currentLambdaExpression.Body == previousNode.Expression)
                            {
                                lambdaBody = Expression.Lambda(lambdaBody, currentLambdaExpression.Parameters);
                                wasNodeHandled = true;
                            }
                            break;

                        case ConditionalExpression currentConditionalExpression:
                            if (currentConditionalExpression.Test == previousNode.Expression)
                            {
                                lambdaBody = Expression.Condition(lambdaBody, currentConditionalExpression.IfTrue, currentConditionalExpression.IfFalse, currentConditionalExpression.Type);
                                wasNodeHandled = true;
                            }
                            else if (currentConditionalExpression.IfTrue == previousNode.Expression)
                            {
                                lambdaBody = Expression.Condition(currentConditionalExpression.Test, lambdaBody, currentConditionalExpression.IfFalse, currentConditionalExpression.Type);
                                wasNodeHandled = true;
                            }
                            else if (currentConditionalExpression.IfFalse == previousNode.Expression)
                            {
                                lambdaBody = Expression.Condition(currentConditionalExpression.Test, currentConditionalExpression.IfTrue, lambdaBody, currentConditionalExpression.Type);
                                wasNodeHandled = true;
                            }
                            break;

                        default:
                            break;
                    }

                    if (!wasNodeHandled)
                    {
                        return false;
                    }

                    previousNode = currentNode;
                    currentNode = currentNode.Parent;
                }

                innerQueryable = dbSetQueryable.Provider.CreateQuery(Expression.Call(
                    null,
                    QueryableMethods.Select.MakeGenericMethod(firstNavigationType, memberPropertyInfo.PropertyType),
                    dbSetQueryable.Expression,
                    Expression.Lambda(lambdaBody, rootParameter)
                ));
            }

            var (innerSql, innerSqlParameters) = innerQueryable.ToParametrizedSql();
            innerSql = innerSql.Trim();

            string firstNavigationAlias = null;
            var rootTableNameWithBrackets = $"[{rootTypeTableInfo.TableName}]";
            var rootTableAliasWithBrackets = $"[{createBodyData.TableAlias}]";
            var firstNavigationTableNameWithBrackets = $"[{firstNavigationTableName}]";
            foreach (Match match in TableAliasPattern.Matches(innerSql))
            {
                var tableName = match.Groups[1].Value;
                var originalAlias = match.Groups[2].Value;

                if (isFirstNavigationACollectionType
                    && tableName.Equals(rootTableNameWithBrackets, StringComparison.OrdinalIgnoreCase)
                    && originalAlias.Equals(rootTableAliasWithBrackets, StringComparison.OrdinalIgnoreCase))
                {
                    // Don't rename this alias, and cut off the unnecessary FROM clause
                    innerSql = innerSql.Substring(0, match.Index);
                    continue;
                }

                if (!createBodyData.TableAliasesInUse.Contains(originalAlias))
                {
                    if (tableName.Equals(firstNavigationTableNameWithBrackets, StringComparison.OrdinalIgnoreCase))
                    {
                        firstNavigationAlias = originalAlias;
                    }

                    createBodyData.TableAliasesInUse.Add(originalAlias);
                    continue;
                }

                var aliasIndex = -1;
                var aliasPrefix = originalAlias.Substring(0, originalAlias.Length - 1);
                string newAlias;
                do
                {
                    ++aliasIndex;
                    newAlias = $"{aliasPrefix}{aliasIndex}]";
                }
                while (createBodyData.TableAliasesInUse.Contains(newAlias));

                createBodyData.TableAliasesInUse.Add(newAlias);
                innerSql = innerSql.Replace(originalAlias, newAlias);

                if (tableName.Equals(firstNavigationTableNameWithBrackets, StringComparison.OrdinalIgnoreCase))
                {
                    firstNavigationAlias = newAlias;
                }
            }

            if (isFirstNavigationACollectionType)
            {
                innerSql = innerSql.Substring(6).Trim();
                
                if (innerSql.StartsWith("("))
                {
                    createBodyData.UpdateColumnsSql.Append(' ').Append(innerSql);
                }
                else
                {
                    createBodyData.UpdateColumnsSql.Append(" (").Append(innerSql).Append(')');
                }

                createBodyData.SqlParameters.AddRange(innerSqlParameters);
                return true;
            }

            var whereClauseCondition = new StringBuilder("WHERE ");
            var dependencyKeyProperties = firstNavigation.ForeignKey.Properties;
            var principalKeyProperties = firstNavigation.ForeignKey.PrincipalKey.Properties;
            var navigationColumnFastLookup = createBodyData.GetTableInfoForType(firstNavigationType).PropertyColumnNamesDict;
            var columnNameValueDict = rootTypeTableInfo.PropertyColumnNamesDict;
            var rootTableAlias = createBodyData.TableAlias;
            if (firstNavigation.IsOnDependent)
            {
                for (int keyIndex = 0; keyIndex < dependencyKeyProperties.Count; ++keyIndex)
                {
                    if (keyIndex > 0)
                    {
                        whereClauseCondition.Append(" AND ");
                    }

                    var dependencyColumnName = navigationColumnFastLookup[dependencyKeyProperties[keyIndex].Name];
                    var principalColumnName = columnNameValueDict[principalKeyProperties[keyIndex].Name];
                    whereClauseCondition.Append(firstNavigationAlias).Append(".[").Append(principalColumnName).Append("] = [")
                        .Append(rootTableAlias).Append("].[").Append(dependencyColumnName).Append(']');
                }
            }
            else
            {
                for (int keyIndex = 0; keyIndex < dependencyKeyProperties.Count; ++keyIndex)
                {
                    if (keyIndex > 0)
                    {
                        whereClauseCondition.Append(" AND ");
                    }

                    var dependencyColumnName = navigationColumnFastLookup[dependencyKeyProperties[keyIndex].Name];
                    var principalColumnName = columnNameValueDict[principalKeyProperties[keyIndex].Name];
                    whereClauseCondition.Append(firstNavigationAlias).Append(".[").Append(dependencyColumnName).Append("] = [")
                        .Append(rootTableAlias).Append("].[").Append(principalColumnName).Append(']');
                }
            }

            var whereClauseIndex = innerSql.LastIndexOf("WHERE ", StringComparison.OrdinalIgnoreCase);
            if (whereClauseIndex > -1)
            {
                innerSql = innerSql.Substring(0, whereClauseIndex) + whereClauseCondition.ToString() + "AND " + innerSql.Substring(whereClauseIndex + 5);
            }
            else
            {
                var orderByIndex = innerSql.LastIndexOf("ORDER BY ", StringComparison.OrdinalIgnoreCase);
                if (orderByIndex > -1)
                {
                    innerSql = innerSql.Substring(0, orderByIndex) + '\n' + whereClauseCondition.ToString() + '\n' + innerSql.Substring(orderByIndex);
                }
                else
                {
                    innerSql = innerSql + '\n' + whereClauseCondition.ToString();
                }

            }

            createBodyData.UpdateColumnsSql.Append(" (\n    ").Append(innerSql.Replace("\n", "\n    ")).Append(')');
            createBodyData.SqlParameters.AddRange(innerSqlParameters);

            return true;
        }

19 View Source File : MethodCallArgumentResolutionVisitor.cs
License : MIT License
Project Creator : brthor

protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node.Method.Name == nameof(TaskExtensions.T)
                && node.Method.DeclaringType == typeof(TaskExtensions))
            {
                node = (MethodCallExpression) node.Arguments[0];
            }

            var argumentExpressions = new List<Expression>();
            foreach (var argument in node.Arguments)
            {
                var argumentResolver = Expression.Lambda(argument);
                var argumentValue = argumentResolver.Compile().DynamicInvoke();

                var valueExpression = Expression.Constant(argumentValue, argument.Type);
                argumentExpressions.Add(valueExpression);
            }
            
            return Expression.Call(node.Object, node.Method, argumentExpressions);
        }

19 View Source File : ObjectMapper.cs
License : Apache License 2.0
Project Creator : busterwood

static LambdaExpression CreateMappingLambda(Type inType, Type outType, List<Mapping<Thing, Thing>> mapping)
        {
            Contract.Requires(mapping != null);
            Contract.Requires(outType != null);
            Contract.Requires(inType != null);
            Contract.Ensures(Contract.Result<LambdaExpression>() != null);

            if (outType.IsClreplaced && outType.GetConstructor(Type.EmptyTypes) == null)
                throw new ArgumentException("Output type must have a parameterless constructor");

            var from = Expression.Parameter(inType, "from");
            var to = Expression.Parameter(outType, "to");
            var result = Expression.Parameter(outType, "result");

            var lines = new List<Expression>();
            if (outType.IsClreplaced)
            {
                // result = to ?? new outType
                lines.Add(Expression.replacedign(result, Expression.Coalesce(to, Expression.New(outType.GetConstructor(Type.EmptyTypes)))));
            }
            foreach (var map in mapping)
            {
                Expression readValue = ReadValue(from, map);
                lines.Add(Expression.replacedign(Expression.PropertyOrField(result, map.To.Name), readValue));
            }
            lines.Add(result); // the return value

            var variables = new[] { result };
            var body = Expression.Block(variables, lines);
            var delegateType = typeof(Func<,,>).MakeGenericType(new[] { inType, outType, outType });
            return Expression.Lambda(delegateType, body, new[] { from, to });
        }

See More Examples