Here are the examples of the csharp api System.Linq.Expressions.Expression.Assign(System.Linq.Expressions.Expression, System.Linq.Expressions.Expression) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
751 Examples
19
View Source File : CommonExpressionMeta.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static Expression Block_MapReaderAndContextreplacedignLocalReaderAndContext(Expression map)
{
return Expression.Block(
Expression.replacedign(Par_Reader, Expression.Property(map, nameof(IMapDataSource<int, int>.Reader))),
Expression.replacedign(Par_DeserializeContext, Expression.Property(map, nameof(IMapDataSource<int, int>.Context)))
);
}
19
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
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
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
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
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
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
License : MIT License
Project Creator : 1996v
private static Expression For(ParameterExpression loopVar, Expression condition, Expression increment, Expression loopContent)
{
var initreplacedign = Expression.replacedign(loopVar, Expression.Constant(0));
var breakLabel = Expression.Label("LoopBreak");
var loop = Expression.Block(
initreplacedign,
Expression.Loop(
Expression.IfThenElse(
condition,
Expression.Block(
loopContent,
increment
),
Expression.Break(breakLabel)
),
breakLabel)
);
return loop;
}
19
View Source File : Array3CodeGenResolver.cs
License : MIT License
Project Creator : 1996v
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 : ICollectionResolver.cs
License : MIT License
Project Creator : 1996v
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 : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();/new T(map.Count)
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = ctor(map.Count);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
//MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
private static void GenerateDeserializeWithGenericDictCore(Type keyType, Type valueType, Func<MemberExpression, Expression> ctor)
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();/new T(map.Count)
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(keyType, valueType));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(keyType, valueType)));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = ctor(map.Count);
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, ctor(Expression.Property(map, nameof(BssMapObjMarshalReader<int, int>.Count)))));
//MapFormatterHelper.FillData(map,(ICollection<KeyValuePair<TKey, TValue>>)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillGenericIDictionaryData), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(keyType, valueType), map, Expression.Convert(instance, typeof(ICollection<>).MakeGenericType(typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static void GenerateDeserializeWithIDictionaryEmptyCtor()
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = new T();
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, Expression.New(t)));
//MapFormatterHelper.FillData(map,(IDictionary)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : IDictionaryResolver.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static void GenerateDeserializeWithIDictionaryEmptyCtor()
{
/*
var map = MapFormatterHelper.Deserialize(ref reader,ref context);
if (map == null)
return null;
context.option.Security.DepthStep(ref reader);
T t = new T();
Deserialize(IEnumerable<KeyValuePair<TKey, TValue>> pair,(ICollection<KeyValuePair<TKey, TValue>>)t);
reader = map.Reader; context = map.Context;
reader.Seek(map.EndPos);
context.Depth--;
return t;
*/
ArrayPack<Expression> ary = new ArrayPack<Expression>(10);
Type t = typeof(T);
LabelTarget returnTarget = Expression.Label(t, "returnLable");
ParameterExpression map = Expression.Variable(typeof(IMapDataSource<,>).MakeGenericType(typeof(object), typeof(object)));
//map = MapFormatterHelper.Deserialize(ref reader,ref context);
ary.Add(Expression.replacedign(map, CommonExpressionMeta.Call_MapFormatterHelper_Deserialize(typeof(object), typeof(object))));
//if (map == null)
// goto label;
ary.Add(Expression.IfThen(Expression.Equal(map, Expression.Constant(null, map.Type)), Expression.Return(returnTarget, Expression.Default(t))));
//context.option.Security.DepthStep(ref reader);
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Option_Security_DepthStep);
//T t = new T();
ParameterExpression instance = Expression.Variable(t);
ary.Add(Expression.replacedign(instance, Expression.New(t)));
//MapFormatterHelper.FillData(map,(IDictionary)t)
ary.Add(Expression.Call(null, typeof(MapFormatterHelper).GetMethod(nameof(MapFormatterHelper.FillIDictionaryData), BindingFlags.Public | BindingFlags.Static), map, Expression.Convert(instance, typeof(IDictionary))));
//reader = map.Reader; context = map.Context;
ary.Add(CommonExpressionMeta.Block_MapReaderAndContextreplacedignLocalReaderAndContext(map));
//reader.Seek(map.EndPos);
ary.Add(CommonExpressionMeta.Call_Reader_BufferSeek(Expression.Property(map, nameof(IMapDataSource<int, int>.EndPosition))));
//context.Depth--;
ary.Add(CommonExpressionMeta.Call_DeserializeContext_Depth_Decrementreplacedign);
//return t;
ary.Add(Expression.Return(returnTarget, instance));
//label default(T)
ary.Add(Expression.Label(returnTarget, instance));
BlockExpression block = Expression.Block(new ParameterExpression[] { map, instance }, ary.GetArray());
Deserialize = Expression.Lambda<Deserialize<T>>(block, CommonExpressionMeta.Par_Reader, CommonExpressionMeta.Par_DeserializeContext).Compile();
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static Func<T, Dictionary<string, string>> CompileSerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "original");
var o_get_object_data = o_t.GetMethod("GetObjectData");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d"); // define object variable
var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
var d_add = d_t.GetMethod("Add"); // add method
var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_get_enumerator = info_t.GetMethod("GetEnumerator");
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(SerializationInfoEnumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_name = Expression.Property(enumerator, "Name");
var enumerator_value = Expression.Property(enumerator, "Value");
var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { d, fc, info, ctx },
Expression.replacedign(d, d_init),
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.Call(o, o_get_object_data, info, ctx),
Expression.Block(new[] { enumerator },
Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_move_next), // test
Expression.IfThen(
Expression.NotEqual(enumerator_value, Expression.Constant(null)),
Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
),
Expression.Break(exit_loop)), // if false
exit_loop)),
d); // return
// compile
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static Func<Dictionary<string, string>, T> CompileDeserializer()
{
var o_t = typeof(T);
var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");
var fc_t = typeof(IFormatterConverter);// typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(typeof(System.Runtime.Serialization.FormatterConverter))); //Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_current = Expression.Property(enumerator, "Current");
var kvp_t = typeof(KeyValuePair<string, string>);
var kvp_pi_key = kvp_t.GetProperty("Key");
var kvp_pi_value = kvp_t.GetProperty("Value");
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { fc, info, ctx, enumerator },
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_mi_move_next),
Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
Expression.Break(exit_loop)),
exit_loop),
Expression.MemberInit(Expression.New(o_ctor, info, ctx))
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static Func<T, Dictionary<string, string>> CompilePropertySerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "o");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d");
var d_init = Expression.MemberInit(Expression.New(d_t));
var d_add = d_t.GetMethod("Add");
var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
.Where(x => x.CanRead)
.Select(x =>
{
var prop = Expression.Property(o, x.Name);
var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));
if (!x.PropertyType.IsByRef)
return (Expression)add_to_dict;
else
return (Expression)Expression.IfThen(
Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
add_to_dict);
});
// run this
var body = Expression.Block(new[] { d }, // scope variables
Expression.replacedign(d, d_init), // initialize
Expression.Block(d_setters), // set
d); // return
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
View Source File : Serializer.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
{
var o_t = typeof(T);
var o = Expression.Variable(o_t, "o");
var o_new = Expression.New(typeof(T));
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_try_get_value = d_t.GetMethod("TryGetValue");
var item_t = typeof(String);
var item = Expression.Variable(item_t, "item");
var tc_t = typeof(TypeConverter);
var tc = Expression.Variable(tc_t, "tc");
var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });
var td_t = typeof(TypeDescriptor);
var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });
var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanRead)
.Select(x =>
{
var value_t = x.PropertyType;
var value = Expression.Variable(value_t, "value");
var target = Expression.Label(x.PropertyType);
return Expression.Bind(x, Expression.Block(new[] { item, value },
Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
Expression.IfThen(
Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
Expression.IfThen(
Expression.NotEqual(item, Expression.Constant(null)),
Expression.IfThen(
Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
Expression.Block(
Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
Expression.Return(target, value, x.PropertyType))))),
Expression.Label(target, value)
));
}).ToArray();
var body = Expression.Block(new[] { o, tc },
Expression.MemberInit(o_new, binds)
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
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 : DbContextAsync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async internal Task ExecCommandAsync() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, Task<int>> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(Task<int>));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
new[] { var1Vals },
Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Func<Task> funcDelete = async () => {
_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
states.Clear();
};
Func<Task> funcInsert = async () => {
_affrows += await dbContextBetch("DbContextBetchAddAsync");
states.Clear();
};
Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
var affrows = 0;
if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
await funcInsert();
break;
case ExecCommandInfoType.Delete:
await funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
await funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
19
View Source File : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099
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 : DbContextSync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void ExecCommand() {
if (isExecCommanding) return;
if (_actions.Any() == false) return;
isExecCommanding = true;
ExecCommandInfo oldinfo = null;
var states = new List<object>();
Func<string, int> dbContextBetch = methodName => {
if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
trydic = new Dictionary<string, Func<object, object[], int>>();
if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
var arrType = oldinfo.stateType.MakeArrayType();
var dbsetType = oldinfo.dbSet.GetType().BaseType;
var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);
var returnTarget = Expression.Label(typeof(int));
var parm1DbSet = Expression.Parameter(typeof(object));
var parm2Vals = Expression.Parameter(typeof(object[]));
var var1Vals = Expression.Variable(arrType);
tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
new[] { var1Vals },
Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
Expression.Label(returnTarget, Expression.Default(typeof(int)))
), new[] { parm1DbSet, parm2Vals }).Compile();
trydic.Add(methodName, tryfunc);
}
return tryfunc(oldinfo.dbSet, states.ToArray());
};
Action funcDelete = () => {
_affrows += dbContextBetch("DbContextBetchRemove");
states.Clear();
};
Action funcInsert = () => {
_affrows += dbContextBetch("DbContextBetchAdd");
states.Clear();
};
Action<bool> funcUpdate = isLiveUpdate => {
var affrows = 0;
if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
else affrows = dbContextBetch("DbContextBetchUpdate");
if (affrows == -999) { //最后一个元素已被删除
states.RemoveAt(states.Count - 1);
return;
}
if (affrows == -998 || affrows == -997) { //没有执行更新
var laststate = states[states.Count - 1];
states.Clear();
if (affrows == -997) states.Add(laststate); //保留最后一个
}
if (affrows > 0) {
_affrows += affrows;
var islastNotUpdated = states.Count != affrows;
var laststate = states[states.Count - 1];
states.Clear();
if (islastNotUpdated) states.Add(laststate); //保留最后一个
}
};
while (_actions.Any() || states.Any()) {
var info = _actions.Any() ? _actions.Dequeue() : null;
if (oldinfo == null) oldinfo = info;
var isLiveUpdate = false;
if (_actions.Any() == false && states.Any() ||
info != null && oldinfo.actionType != info.actionType ||
info != null && oldinfo.stateType != info.stateType) {
if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
//最后一个,合起来发送
states.Add(info.state);
info = null;
}
switch (oldinfo.actionType) {
case ExecCommandInfoType.Insert:
funcInsert();
break;
case ExecCommandInfoType.Delete:
funcDelete();
break;
}
isLiveUpdate = true;
}
if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
if (states.Any())
funcUpdate(isLiveUpdate);
}
if (info != null) {
states.Add(info.state);
oldinfo = info;
}
}
isExecCommanding = false;
}
19
View Source File : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099
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 : LetClause.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
protected override Expression Reduce(QueryClause previous, QueryClause next)
{
return Expression.Block(new[] { Variable },
Expression.replacedign(Variable, Expression),
next.Reduce()
);
}
19
View Source File : ForExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override Expression Reduce()
{
var inner_loop_break = Label("inner_loop_break");
var inner_loop_continue = Label("inner_loop_continue");
var @continue = ContinueLabel ?? Label("continue");
var @break = BreakLabel ?? Label("break");
return Block(
new [] { Variable },
replacedign(Variable, Initializer),
Loop(
Block(
IfThen(
IsFalse(Test),
Break(inner_loop_break)),
Body,
Label(@continue),
Step),
inner_loop_break,
inner_loop_continue),
Label(@break));
}
19
View Source File : ExpressionVisitor`1.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
protected void EnableDynamicVisiting()
{
if (dynamicVisit != null)
return;
Type returnType = typeof(T);
ParameterExpression exprParam = Expression.Parameter(typeof(Expression), "node");
Expression body = Expression.Call(Expression.Constant(this), nameof(DefaultVisit), null, exprParam);
foreach (MethodInfo method in this.GetType().GetTypeInfo().DeclaredMethods)
{
if (method.ReturnType != returnType || !method.Name.StartsWith("Visit"))
continue;
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length != 1)
continue;
ParameterInfo parameter = parameters[0];
if (!parameter.ParameterType.IsreplacedignableTo(typeof(Expression)))
continue;
// We got this far, it's a valid Visit*() method.
ParameterExpression exprVar = Expression.Parameter(parameter.ParameterType, parameter.Name);
// expr is TExpr newExpr ? newExpr : body
body = Expression.Block(new[] { exprVar },
Expression.replacedign(exprVar, Expression.TypeAs(exprParam, parameter.ParameterType)),
Expression.Condition(
Expression.ReferenceNotEqual(exprVar, Expression.Constant(null)),
exprVar,
body
)
);
}
dynamicVisit = Expression.Lambda<Func<Expression, T>>(body, exprParam).Compile();
}
19
View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private Expression ReduceForArray()
{
LabelTarget inner_loop_break = Label("inner_loop_break");
LabelTarget inner_loop_continue = Label("inner_loop_continue");
LabelTarget @continue = ContinueLabel ?? Label("continue");
LabelTarget @break = BreakLabel ?? Label("break");
ParameterExpression index = Variable(typeof(int), "i");
return Block(
new [] { index, Variable },
replacedign(index, Constant(0)),
Loop(
Block(
IfThen(
IsFalse(LessThan(index, ArrayLength(Enumerable))),
Break(inner_loop_break)
),
replacedign(Variable, Convert(ArrayIndex(Enumerable, index), Variable.Type)),
Body,
Label(@continue),
PreIncrementreplacedign(index)
),
inner_loop_break,
inner_loop_continue
),
Label(@break)
);
}
19
View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private Expression ReduceForEnumerable()
{
MethodInfo get_enumerator;
MethodInfo get_current;
ResolveEnumerationMembers(out get_enumerator, out get_current);
Type enumerator_type = get_enumerator.ReturnType;
ParameterExpression enumerator = Variable(enumerator_type);
LabelTarget inner_loop_continue = Label("inner_loop_continue");
LabelTarget inner_loop_break = Label("inner_loop_break");
LabelTarget @continue = ContinueLabel ?? Label("continue");
LabelTarget @break = BreakLabel ?? Label("break");
Expression variable_initializer = Property(enumerator, get_current);
if (!Variable.Type.GetTypeInfo().IsreplacedignableFrom(get_current.ReturnType.GetTypeInfo()))
variable_initializer = Convert(variable_initializer, Variable.Type);
Expression loop = Block(
new [] { Variable },
Goto(@continue),
Loop(
Block(
replacedign(Variable, variable_initializer),
Body,
Label(@continue),
Condition(
Call(enumerator, Reflection.IEnumerator_MoveNext),
Goto(inner_loop_continue),
Goto(inner_loop_break)
)
),
inner_loop_break,
inner_loop_continue
),
Label(@break)
);
Expression dispose = CreateDisposeOperation(enumerator_type.GetTypeInfo(), enumerator);
return Block(
new [] { enumerator },
replacedign(enumerator, Call(Enumerable, get_enumerator)),
dispose != null ? TryFinally(loop, dispose) : loop
);
}
19
View Source File : TrackingExpressionVisitor.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public Expression GenerateBody(Expression body, Expression vsmExpression)
{
Debug.replacedert(vsmExpression.Type.IsreplacedignableTo<VirtualStateMachine>());
if (Variables.Count == 0)
return body;
Expression[] loadVariableExpressions = new Expression[Variables.Count];
Expression[] saveVariableExpressions = new Expression[Variables.Count];
Expression localsExpression = Expression.Field(vsmExpression, VirtualStateMachine.LocalsField);
for (int i = 0; i < Variables.Count; i++)
{
ParameterExpression variable = Variables[i];
loadVariableExpressions[i] = Expression.replacedign(
variable, Expression.Convert(
Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
variable.Type
)
);
saveVariableExpressions[i] = Expression.replacedign(
Expression.ArrayAccess(localsExpression, Expression.Constant(i)),
Expression.Convert(variable, typeof(object))
);
}
Expression init = loadVariableExpressions.Length == 0
? (Expression)Expression.Empty() : Expression.Block(typeof(void), loadVariableExpressions);
Expression end = saveVariableExpressions.Length == 0
? (Expression)Expression.Empty() : Expression.Block(typeof(void), saveVariableExpressions);
if (body.Type == typeof(void))
return Expression.Block(Variables, init, body, end);
ParameterExpression result = Expression.Variable(body.Type, "result");
return Expression.Block(Variables.Prepend(result), init, Expression.replacedign(result, body), end, result);
}
19
View Source File : ForEachExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Expression CreateDisposeOperation (TypeInfo enumerator_type, ParameterExpression enumerator)
{
if (Reflection.IDisposable.IsreplacedignableFrom(enumerator_type))
return Call(enumerator, Reflection.IDisposable_Dispose);
if (enumerator_type.IsValueType)
return null;
ParameterExpression disposable = Variable(typeof(IDisposable));
return Block(
new [] { disposable },
replacedign(disposable, TypeAs(enumerator, typeof(IDisposable))),
IfThen(ReferenceNotEqual(disposable, Constant(null)),
Call(disposable, Reflection.IDisposable_Dispose)
)
);
}
19
View Source File : StateMachineExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
protected LambdaExpression GenerateLambda(Expression body, params ParameterExpression[] parameters)
{
body = trackingVisitor.Visit(body);
// Create the switch cases to go to our previous state.
LabelTarget[] targets = labelTargets.ToArray();
SwitchCase[] cases = new SwitchCase[targets.Length + 1];
LabelTarget startLabel = Label("start");
cases[0] = SwitchCase(Goto(startLabel), Constant(0));
for (int i = 1; i < cases.Length; i++)
{
cases[i] = SwitchCase(Goto(targets[i - 1]), Constant(i));
}
// Add a switch to the beginning of the body
body = Block(
Switch(
Field(State, VirtualStateMachine.StateField),
Throw(New(typeof(ArgumentOutOfRangeException))),
cases
),
Label(startLabel),
body,
replacedign(Field(State, VirtualStateMachine.StateField), Constant(cases.Length)),
Label(End, Default(End.Type))
);
return Lambda(
trackingVisitor.GenerateBody(body, State),
parameters.Prepend(State)
);
}
19
View Source File : StateMachineExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
protected Expression Return(Expression value)
{
int nth = labelTargets.Count + 1;
LabelTarget label = Label($"L{nth}");
labelTargets.Add(label);
return Block(
replacedign(Field(State, VirtualStateMachine.StateField), Constant(nth)),
Return(End, value),
Label(label)
);
}
19
View Source File : LinkedExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
private static Action<T> GetCompiledSetter(Expression<Func<T>> lambda)
{
ParameterExpression parameter = Parameter(typeof(T), "value");
return Lambda<Action<T>>(replacedign(lambda.Body, parameter), parameter).Compile();
}
19
View Source File : LockExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override Expression Reduce()
{
ParameterExpression lockObject = Variable(typeof(object), "lockObject");
return Block(new[] { lockObject },
replacedign(lockObject, Object),
TryFinally(
Block(
Call(typeof(Monitor), nameof(Monitor.Enter), null, lockObject),
Body
),
Call(typeof(Monitor), nameof(Monitor.Exit), null, lockObject)
)
);
}
19
View Source File : UsingExpression.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
public override Expression Reduce()
{
var end_finally = Label("end_finally");
return Block (
new [] { Variable },
replacedign(Variable, Disposable),
TryFinally(
Body,
Block(
Condition(
NotEqual(Variable, Constant(null)),
Block(
Call(Convert(Variable, typeof(IDisposable)), Reflection.IDisposable_Dispose),
Goto(end_finally)
),
Goto(end_finally)
),
Label(end_finally)
)
)
);
}
19
View Source File : DataContext.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public void Import<T>(Expression<Func<T>> propertyExpression, string key = null)
{
var parameter = Expression.Parameter(typeof(T));
var setter = Expression.Lambda<Action<T>>(
Expression.replacedign(
propertyExpression.Body,
parameter),
parameter).Compile();
key = key ?? PropertySupport.ExtractPropertyName(propertyExpression);
if (!_importPropertySetterDictionary.ContainsKey(key))
{
_importPropertySetterDictionary.Add(key, new List<Delegate>());
}
_importPropertySetterDictionary[key].Add(setter);
}
19
View Source File : Serializer.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
static Func<T, Dictionary<string, string>> CompileSerializer()
{
var o_t = typeof(T);
var o = Expression.Parameter(o_t, "original");
var o_get_object_data = o_t.GetMethod("GetObjectData");
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Variable(d_t, "d"); // define object variable
var d_init = Expression.MemberInit(Expression.New(d_t)); // object ctor
var d_add = d_t.GetMethod("Add"); // add method
var fc_t = typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_get_enumerator = info_t.GetMethod("GetEnumerator");
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(SerializationInfoEnumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_name = Expression.Property(enumerator, "Name");
var enumerator_value = Expression.Property(enumerator, "Value");
var mi_to_string = typeof(Object).GetMethod("ToString", new Type[0]);
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { d, fc, info, ctx },
Expression.replacedign(d, d_init),
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.Call(o, o_get_object_data, info, ctx),
Expression.Block(new[] { enumerator },
Expression.replacedign(enumerator, Expression.Call(info, info_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_move_next), // test
Expression.IfThen(
Expression.NotEqual(enumerator_value, Expression.Constant(null)),
Expression.Call(d, d_add, enumerator_name, Expression.Call(enumerator_value, mi_to_string))
),
Expression.Break(exit_loop)), // if false
exit_loop)),
d); // return
// compile
return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
.Compile();
}
19
View Source File : Serializer.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
static Func<Dictionary<string, string>, T> CompileDeserializer()
{
var o_t = typeof(T);
var o_ctor = o_t.GetConstructor(new[] { typeof(SerializationInfo), typeof(StreamingContext) });
var d_t = typeof(Dictionary<string, string>);
var d = Expression.Parameter(d_t, "d");
var d_mi_get_enumerator = d_t.GetMethod("GetEnumerator");
var fc_t = typeof(LocalVariableInfo);
var fc = Expression.Variable(fc_t, "fc");
var fc_init = Expression.MemberInit(Expression.New(fc_t));
var info_t = typeof(SerializationInfo);
var info = Expression.Variable(info_t, "info");
var info_ctor = info_t.GetConstructor(new[] { typeof(Type), fc_t });
var info_init = Expression.MemberInit(Expression.New(info_ctor, Expression.Constant(o_t), fc));
var info_mi_add_value = info_t.GetMethod("AddValue", new[] { typeof(String), typeof(Object) });
var ctx_t = typeof(StreamingContext);
var ctx = Expression.Variable(ctx_t, "ctx");
var ctx_init = Expression.MemberInit(Expression.New(ctx_t));
var enumerator_t = typeof(Dictionary<string, string>.Enumerator);
var enumerator = Expression.Variable(enumerator_t, "enumerator");
var enumerator_mi_move_next = enumerator_t.GetMethod("MoveNext");
var enumerator_current = Expression.Property(enumerator, "Current");
var kvp_t = typeof(KeyValuePair<string, string>);
var kvp_pi_key = kvp_t.GetProperty("Key");
var kvp_pi_value = kvp_t.GetProperty("Value");
var exit_loop = Expression.Label("exit_loop");
var body = Expression.Block(new[] { fc, info, ctx, enumerator },
Expression.replacedign(fc, fc_init),
Expression.replacedign(info, info_init),
Expression.replacedign(ctx, ctx_init),
Expression.replacedign(enumerator, Expression.Call(d, d_mi_get_enumerator)),
Expression.Loop(
Expression.IfThenElse(
Expression.Call(enumerator, enumerator_mi_move_next),
Expression.Call(info, info_mi_add_value, Expression.Property(enumerator_current, kvp_pi_key), Expression.Property(enumerator_current, kvp_pi_value)),
Expression.Break(exit_loop)),
exit_loop),
Expression.MemberInit(Expression.New(o_ctor, info, ctx))
);
return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
.Compile();
}
19
View Source File : ExpressionReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression = new Expression[parametersInfo.Length];
IList<ByRefParameter> refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
{
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
isByRef = true;
}
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression;
if (parameterType.IsValueType())
{
BinaryExpression ensureValueTypeNotNull = Expression.Coalesce(paramAccessorExpression, Expression.New(parameterType));
argExpression = EnsureCastExpression(ensureValueTypeNotNull, parameterType);
}
else
{
argExpression = EnsureCastExpression(paramAccessorExpression, parameterType);
}
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter
{
Value = argExpression,
Variable = variable,
IsOut = parameter.IsOut
});
argExpression = variable;
}
argsExpression[i] = argExpression;
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo)
{
MethodInfo m = (MethodInfo)method;
if (m.ReturnType != typeof(void))
{
callExpression = EnsureCastExpression(callExpression, type);
}
else
{
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
if (refParameterMap.Count > 0)
{
IList<ParameterExpression> variableExpressions = new List<ParameterExpression>();
IList<Expression> bodyExpressions = new List<Expression>();
foreach (ByRefParameter p in refParameterMap)
{
if (!p.IsOut)
{
bodyExpressions.Add(Expression.replacedign(p.Variable, p.Value));
}
variableExpressions.Add(p.Variable);
}
bodyExpressions.Add(callExpression);
callExpression = Expression.Block(variableExpressions, bodyExpressions);
}
return callExpression;
}
19
View Source File : DynamicProxyMetaObject.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter(typeof(object), null);
IList<Expression> callArgs = new List<Expression>();
callArgs.Add(Expression.Convert(Expression, typeof(T)));
callArgs.Add(Constant(binder));
callArgs.AddRange(args);
callArgs[args.Length + 1] = Expression.replacedign(result, callArgs[args.Length + 1]);
DynamicMetaObject callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result },
Expression.Condition(
Expression.Call(
Expression.Constant(_proxy),
typeof(DynamicProxy<T>).GetMethod(methodName),
callArgs
),
result,
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return _dontFallbackFirst ? callDynamic : fallback(callDynamic);
}
19
View Source File : ExpressionReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
{
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
}
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression replacedignExpression = Expression.replacedign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), replacedignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
19
View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
private static Expression ReferenceArgreplacedign (Expression callArgs, Expression[] args)
{
ReadOnlyCollectionBuilder<Expression> block = null;
for (int i = 0; i < args.Length; i++)
{
ParameterExpression variable = args[i] as ParameterExpression;
if (variable.IsByRef)
{
if (block == null)
block = new ReadOnlyCollectionBuilder<Expression> ();
block.Add (
Expression.replacedign (
variable,
Expression.Convert (
Expression.ArrayIndex (
callArgs,
AstUtils.Constant (i)
),
variable.Type
)
)
);
}
}
if (block != null)
return Expression.Block (block);
else
return AstUtils.Empty;
}
19
View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
private DynamicMetaObject BuildCallMethodWithResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback<TBinder> fallbackInvoke)
where TBinder : DynamicMetaObjectBinder
{
if (!IsOverridden (method))
{
return fallbackResult;
}
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter (typeof (object), null);
ParameterExpression callArgs = method != DynamicObject_TryBinaryOperation ? Expression.Parameter (typeof (object[]), null) : Expression.Parameter (typeof (object), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);
var resultMO = new DynamicMetaObject (result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof (object))
{
Debug.replacedert (binder is ConvertBinder && fallbackInvoke == null);
UnaryExpression convert = Expression.Convert (resultMO.Expression, binder.ReturnType);
// will always be a cast or unbox
Debug.replacedert (convert.Method == null);
// Prepare a good exception message in case the convert will fail
// JJA - we don't have access to the Strings type:
//string convertFailed = System.Linq.Expressions.Strings.DynamicObjectResultNotreplacedignable (
// "{0}",
// this.Value.GetType(),
// binder.GetType(),
// binder.ReturnType
//);
string convertFailed = $"Dynamic conversion failed: Could not convert type '{Value.WrappedType}' to '{binder.ReturnType}'.";
Expression condition;
// If the return type can not be replacedigned null then just check for type replacedignability otherwise allow null.
if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType (binder.ReturnType) == null)
{
condition = Expression.TypeIs (resultMO.Expression, binder.ReturnType);
}
else
{
condition = Expression.OrElse (
Expression.Equal (resultMO.Expression, AstUtils.Null),
Expression.TypeIs (resultMO.Expression, binder.ReturnType));
}
Expression checkedConvert = Expression.Condition (
condition,
convert,
Expression.Throw (
Expression.New (
InvalidCastException_Ctor_String,
new TrueReadOnlyCollection<Expression> (
Expression.Call (
String_Format_String_ObjectArray,
Expression.Constant (convertFailed),
Expression.NewArrayInit (
typeof (object),
new TrueReadOnlyCollection<Expression> (
Expression.Condition (
Expression.Equal (resultMO.Expression, AstUtils.Null),
Expression.Constant ("null"),
Expression.Call (
resultMO.Expression,
Object_GetType
),
typeof (object)
)
)
)
)
)
),
binder.ReturnType
),
binder.ReturnType
);
resultMO = new DynamicMetaObject (checkedConvert, resultMO.Restrictions);
}
if (fallbackInvoke != null)
{
resultMO = fallbackInvoke (this, binder, resultMO);
}
var callDynamic = new DynamicMetaObject (
Expression.Block (
new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
new TrueReadOnlyCollection<Expression> (
method != DynamicObject_TryBinaryOperation ? Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)) : Expression.replacedign (callArgs, callArgsValue[0]),
Expression.Condition (
Expression.Call (
GetLimitedSelf (),
method,
BuildCallArgs (
binder,
method.Name == "TryInvokeMember", // JJA
args,
callArgs,
result
)
),
Expression.Block (
method != DynamicObject_TryBinaryOperation ? ReferenceArgreplacedign (callArgs, args) : AstUtils.Empty,
resultMO.Expression
),
fallbackResult.Expression,
binder.ReturnType
)
)
),
GetRestrictions ().Merge (resultMO.Restrictions).Merge (fallbackResult.Restrictions)
);
return callDynamic;
}
19
View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
private DynamicMetaObject CallMethodReturnLast<TBinder> (MethodInfo method, TBinder binder, Expression[] args, Expression value, Fallback<TBinder> fallback)
where TBinder : DynamicMetaObjectBinder
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback (this, binder, null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
ParameterExpression result = Expression.Parameter (typeof (object), null);
ParameterExpression callArgs = Expression.Parameter (typeof (object[]), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);
var callDynamic = new DynamicMetaObject (
Expression.Block (
new TrueReadOnlyCollection<ParameterExpression> (result, callArgs),
new TrueReadOnlyCollection<Expression> (
Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)),
Expression.Condition (
Expression.Call (
GetLimitedSelf (),
method,
BuildCallArgs (
binder,
method.Name == "TryInvokeMember", // JJA
args,
callArgs,
Expression.replacedign (result, Expression.Convert (value, typeof (object)))
)
),
Expression.Block (
ReferenceArgreplacedign (callArgs, args),
result
),
fallbackResult.Expression,
typeof (object)
)
)
),
GetRestrictions ().Merge (fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback (this, binder, callDynamic);
}
19
View Source File : GreedyMetaDynamic.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
private DynamicMetaObject CallMethodNoResult<TBinder> (MethodInfo method, TBinder binder, Expression[] args, Fallback<TBinder> fallback)
where TBinder : DynamicMetaObjectBinder
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback (this, binder, null);
ParameterExpression callArgs = Expression.Parameter (typeof (object[]), null);
ReadOnlyCollection<Expression> callArgsValue = GetConvertedArgs (args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
var callDynamic = new DynamicMetaObject (
Expression.Block (
new TrueReadOnlyCollection<ParameterExpression> (callArgs),
new TrueReadOnlyCollection<Expression> (
Expression.replacedign (callArgs, Expression.NewArrayInit (typeof (object), callArgsValue)),
Expression.Condition (
Expression.Call (
GetLimitedSelf (),
method,
BuildCallArgs (
binder,
method.Name == "TryInvokeMember", // JJA
args,
callArgs,
null
)
),
Expression.Block (
ReferenceArgreplacedign (callArgs, args),
AstUtils.Empty
),
fallbackResult.Expression,
typeof (void)
)
)
),
GetRestrictions ().Merge (fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback (this, binder, callDynamic);
}
19
View Source File : NodePort.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
PushDataDelegate CreatePushDataDelegateForEdge(SerializableEdge edge)
{
try
{
//Creation of the delegate to move the data from the input node to the output node:
FieldInfo inputField = edge.inputNode.GetType().GetField(edge.inputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo outputField = edge.outputNode.GetType().GetField(edge.outputFieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Type inType, outType;
#if DEBUG_LAMBDA
return new PushDataDelegate(() => {
var outValue = outputField.GetValue(edge.outputNode);
inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
outType = edge.outputPort.portData.displayType ?? outputField.FieldType;
Debug.Log($"Push: {inType}({outValue}) -> {outType} | {owner.name}");
object convertedValue = outValue;
if (TypeAdapter.Arereplacedignable(outType, inType))
{
var convertionMethod = TypeAdapter.GetConvertionMethod(outType, inType);
Debug.Log("Convertion method: " + convertionMethod.Name);
convertedValue = convertionMethod.Invoke(null, new object[]{ outValue });
}
inputField.SetValue(edge.inputNode, convertedValue);
});
#endif
// We keep slow checks inside the editor
#if UNITY_EDITOR
if (!BaseGraph.TypesAreConnectable(inputField.FieldType, outputField.FieldType))
{
Debug.LogError("Can't convert from " + inputField.FieldType + " to " + outputField.FieldType + ", you must specify a custom port function (i.e CustomPortInput or CustomPortOutput) for non-implicit convertions");
return null;
}
#endif
Expression inputParamField = Expression.Field(Expression.Constant(edge.inputNode), inputField);
Expression outputParamField = Expression.Field(Expression.Constant(edge.outputNode), outputField);
inType = edge.inputPort.portData.displayType ?? inputField.FieldType;
outType = edge.outputPort.portData.displayType ?? outputField.FieldType;
// If there is a user defined convertion function, then we call it
if (TypeAdapter.Arereplacedignable(outType, inType))
{
// We add a cast in case there we're calling the conversion method with a base clreplaced parameter (like object)
var convertedParam = Expression.Convert(outputParamField, outType);
outputParamField = Expression.Call(TypeAdapter.GetConvertionMethod(outType, inType), convertedParam);
// In case there is a custom port behavior in the output, then we need to re-cast to the base type because
// the convertion method return type is not always replacedignable directly:
outputParamField = Expression.Convert(outputParamField, inputField.FieldType);
}
else // otherwise we cast
outputParamField = Expression.Convert(outputParamField, inputField.FieldType);
BinaryExpression replacedign = Expression.replacedign(inputParamField, outputParamField);
return Expression.Lambda< PushDataDelegate >(replacedign).Compile();
} catch (Exception e) {
Debug.LogError(e);
return null;
}
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
static Expression OneOf(IEnumerable<Expression> expressions)
{
var rsl = Expression.Variable(typeof(bool));
var brk = Expression.Label(typeof(bool));
return Expression.Block(
new[] { rsl },
Expression.Block(
expressions.Select(i =>
Expression.IfThen(i,
Expression.IfThenElse(rsl,
Expression.Return(brk, False),
Expression.replacedign(rsl, True))))),
Expression.Label(brk, rsl));
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
public Expression Build(JSchema schema, Expression token)
{
if (schema == null)
throw new ArgumentNullException(nameof(schema));
if (token == null)
throw new ArgumentNullException(nameof(token));
// evaluate expression
var e = Eval(schema, token);
// if any recursed, generate replacedignment of delegates in block
var v = delayed.Where(i => i.Value != null).ToArray();
if (v.Length > 0)
e = Expression.Block(
v.Select(i => i.Value).ToArray(),
Enumerable.Empty<Expression>()
.Concat(v.Select(i => Expression.replacedign(i.Value, compile[i.Key])))
.Append(e));
return e;
}
19
View Source File : JSchemaExpressionBuilder.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
Expression BuildContains(JSchema schema, Expression o)
{
if (schema.Contains == null)
return null;
var val = Expression.Convert(o, typeof(JArray));
var idx = Expression.Variable(typeof(int));
var brk = Expression.Label(typeof(bool));
var len = Expression.Property(val, nameof(JArray.Count));
return IfThenElseTrue(
IsTokenType(o, JTokenType.Array),
Expression.Block(
new[] { idx },
Expression.replacedign(idx, Expression.Constant(0)),
Expression.Loop(
Expression.IfThenElse(
Expression.Not(Expression.LessThan(idx, len)),
Expression.Break(brk, False),
Expression.IfThenElse(
Eval(schema.Contains, FromItemIndex(val, idx)),
Expression.Break(brk, True),
Expression.PostIncrementreplacedign(idx))),
brk)));
}
19
View Source File : ExpressionBuilderBase.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
protected static Expression OneOf(IEnumerable<Expression> expressions)
{
var rsl = Expression.Variable(typeof(bool));
var brk = Expression.Label(typeof(bool));
return Expression.Block(
new[] { rsl },
Expression.Block(
expressions.Select(i =>
Expression.IfThen(i,
Expression.IfThenElse(rsl,
Expression.Return(brk, False),
Expression.replacedign(rsl, True))))),
Expression.Label(brk, rsl));
}
19
View Source File : IteratorCompiler.cs
License : MIT License
Project Creator : asc-community
License : MIT License
Project Creator : asc-community
private static Expression CreateLoop(ParameterExpression var, Expression until, Expression onIter)
{
var label = Expression.Label();
var loop = Expression.Loop(
Expression.Block(
Expression.IfThenElse(
Expression.LessThan(var, until),
Expression.Block(
onIter
),
Expression.Break(label)
),
Expression.PostIncrementreplacedign(var)
),
label);
return Expression.Block(
Expression.replacedign(var, Expression.Constant(0)),
loop
);
}
See More Examples