public static Convert ( |
||
expression | An |
|
type | Type | A |
return |
Expression ReplaceParameter(IDictionary<Expression,Expression> expressionAccessors, Expression expression, Action<string> setName) { return expression.Convert(expr => { if (expr.NodeType == ExpressionType.Constant) { var c = (ConstantExpression)expr; if (!ExpressionHelper.IsConstant(expr.Type) || _asParameters.Contains(c)) { var val = expressionAccessors[expr]; expr = Expression.Convert(val, expr.Type); if (expression.NodeType == ExpressionType.MemberAccess) { var ma = (MemberExpression)expression; setName(ma.Member.Name); } } } return expr; }); }
private static Func <object, object, object> CreateFunc(string program) { var assemblyName = new AssemblyName(Guid.NewGuid().ToString()) { Version = new Version(1, 0) }; AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Program"); ParameterExpression valueParameter = Expression.Parameter(typeof(object), "value"); ParameterExpression parameterParameter = Expression.Parameter(typeof(object), "parameter"); AstHelper astHelper = AstHelper.Default(moduleBuilder); astHelper.Variables.Add("value", valueParameter); astHelper.Variables.Add("parameter", parameterParameter); Expression rootExpression = ProgramExpression.Compile(astHelper, program); Expression <Func <object, object, object> > lambda = Expression.Lambda <Func <object, object, object> >(Expression.Convert(rootExpression, typeof(object)), valueParameter, parameterParameter); return(lambda.Compile()); }
// Pseudocode: //string input => //{ // R result = 0; // for (int i = input.Length - 1; i >= 0; i--) // { // result <<= 6; // var m = _invMap[input[i]]; // if (m == 0xff) // return default(ConversionResult<R>); // result += m; // } // return new ConversionResult<R>(result); //} private LambdaExpression fromLambda(Type to) { var stringthis = typeof(string).GetTypeInfo().DeclaredProperties.First(p => p.GetIndexParameters().Length == 1 && p.GetIndexParameters()[0].ParameterType == typeof(int)); var input = Ex.Parameter(typeof(string), "input"); var result = Ex.Parameter(to, "result"); var i = Ex.Parameter(typeof(int), "i"); var m = Ex.Parameter(typeof(byte), "m"); var loopstart = Ex.Label("loopstart"); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end"); var loop = Ex.Block( Ex.Label(loopstart), Ex.IfThen(Ex.MakeBinary(ExpressionType.LessThan, i, Ex.Constant(0)), Ex.Goto(end, Result(to, result))), Ex.LeftShiftAssign(result, Ex.Constant(6)), Ex.Assign(m, Ex.ArrayIndex(Ex.Constant(_invMap), Ex.Convert(Ex.MakeIndex(input, stringthis, new[] { i }), typeof(int)))), Ex.IfThen(Ex.MakeBinary(ExpressionType.Equal, m, Ex.Constant((byte)0xff)), Ex.Goto(end, NoResult(to))), Ex.AddAssign(result, Ex.Convert(m, result.Type)), Ex.PostDecrementAssign(i), Ex.Goto(loopstart)); var block = Ex.Block(new[] { result, i, m }, Ex.Assign(result, Ex.Convert(Ex.Constant(0), to)), Ex.Assign(i, Ex.MakeBinary(ExpressionType.Subtract, Ex.Property(input, nameof(string.Length)), Ex.Constant(1))), loop, Ex.Label(end, NoResult(to))); return(Ex.Lambda(block, input)); }
internal bool AddSplattedArgumentTest(object value, Expression /*!*/ expression, out int listLength, out ParameterExpression /*!*/ listVariable) { if (value == null) { AddRestriction(Ast.Equal(expression, Ast.Constant(null))); } else { // test exact type: AddTypeRestriction(value.GetType(), expression); List <object> list = value as List <object>; if (list != null) { Type type = typeof(List <object>); listLength = list.Count; listVariable = GetTemporary(type, "#list"); AddCondition(Ast.Equal( Ast.Property(Ast.Assign(listVariable, Ast.Convert(expression, type)), type.GetProperty("Count")), Ast.Constant(list.Count)) ); return(true); } } listLength = -1; listVariable = null; return(false); }
public static Expression Call(ProcedureCall call) { if (ReferenceEquals(call, null)) { throw new ArgumentNullException(nameof(call)); } var services = Services.Instance; var procedure = services.GetProcedureSignature(call); if (!procedure.HasReturnType) { throw new InvalidOperationException( "Cannot use a procedure that does not return a value."); } var arguments = services.GetArguments(procedure, call.Arguments); var servicesExpr = LinqExpression.Constant(services); var executeCallMethod = typeof(Services).GetMethod( "ExecuteCall", new[] { typeof(Scanner.ProcedureSignature), typeof(object[]) }); var procedureExpr = LinqExpression.Constant(procedure); var argumentsExpr = LinqExpression.Constant(arguments); var result = LinqExpression.Call( servicesExpr, executeCallMethod, new[] { procedureExpr, argumentsExpr }); var value = LinqExpression.Convert( LinqExpression.Property(result, "Value"), procedure.ReturnType); return(new Expression(value)); }
/// <summary> /// Transform as expression (value is read). /// </summary> protected internal override MAst Transform() { if (_innerExpression.Type == typeof(string)) { Expression <Func <string, bool> > result = str => !string.IsNullOrEmpty(str); MAst arg = _innerExpression.Transform(); UnaryExpression converted = arg.Convert <string>(); return(result.eInvoke(converted)); } else if (_innerExpression.Type.IsValueType) { var zero = (ValueType)(Activator.CreateInstance(_innerExpression.Type)); return(MAst.NotEqual(_innerExpression.Transform(), MAst.Constant(zero, _innerExpression.Type))); } else if (_innerExpression.Type == typeof(Null)) { return(MAst.Constant(false, typeof(bool))); } else { Expression <Func <object, bool> > result = o => (o != null); MAst arg = _innerExpression.Transform(); UnaryExpression converted = arg.Convert <object>(); return(result.eInvoke(converted)); } }
public static Expression Power(Expression arg0, Expression arg1) { var arg0b = LinqExpression.Convert(arg0, typeof(double)); var arg1b = LinqExpression.Convert(arg1, typeof(double)); return(new Expression(LinqExpression.Convert(LinqExpression.Power(arg0b, arg1b), arg0.Type))); }
private static TSetLambda CreateSetter <TGetLambda, TSetLambda>( this Expression <TGetLambda> getter, Type propertyType) { var memberExpression = (MemberExpression)getter.Body; var property = (PropertyInfo)memberExpression.Member; var setMethod = property.GetSetMethod(); if (setMethod == null) { return(default(TSetLambda)); } var parameterValue = Expression.Parameter(propertyType); var callParameter = Equals(propertyType, memberExpression.Type) ? (Expression)parameterValue : Expression.Convert(parameterValue, memberExpression.Type); var newExpression = Expression.Lambda <TSetLambda>( Expression.Call(memberExpression.Expression, setMethod, callParameter), getter.Parameters.Concat(new[] { parameterValue }) ); return(newExpression.Compile()); }
private static Accessor GetAccessor <TAttribute>(Type targetType) where TAttribute : Attribute { Accessor accessor; var cache = GetCache <TAttribute>(); if (cache.TryGetValue(targetType, out accessor)) { return(accessor); } var member = FindMember <TAttribute>(targetType); if (member == null) { cache[targetType] = NullCallback; return(NullCallback); } var targetParameter = E.Parameter(typeof(object), "target"); var accessorExpression = E.Lambda <Accessor>( E.Convert( E.MakeMemberAccess( E.Convert(targetParameter, targetType), member), typeof(object)), targetParameter); accessor = accessorExpression.Compile(); cache[targetType] = accessor; return(accessor); }
protected override ExpressionBody Transform(Ast.LambdaExpression lmx) { var parameters = lmx.Parameters.Select(px => Tuple.Create(px, LX.Parameter(typeof(LogEventPropertyValue), px.ParameterName))).ToList(); var paramSwitcher = new ExpressionConstantMapper(parameters.ToDictionary(px => (object)px.Item1, px => (System.Linq.Expressions.Expression)px.Item2)); var rewritten = paramSwitcher.Visit(Transform(lmx.Body)); Type delegateType; if (lmx.Parameters.Length == 1) { delegateType = typeof(Func <LogEventPropertyValue, LogEventPropertyValue>); } else if (lmx.Parameters.Length == 2) { delegateType = typeof(Func <LogEventPropertyValue, LogEventPropertyValue, LogEventPropertyValue>); } else { throw new NotSupportedException("Unsupported lambda signature."); } var lambda = LX.Lambda(delegateType, rewritten !, parameters.Select(px => px.Item2).ToArray()); // Unfortunately, right now, functions need to be threaded through in constant scalar values :-D return(LX.New(typeof(ScalarValue).GetConstructor(new[] { typeof(object) }) !, LX.Convert(lambda, typeof(object)))); }
public LambdaExpression CreateLambda(Type from, Type to) { var input = Ex.Parameter(from, "input"); var fromInfo = infos[from]; var toInfo = infos[to]; if (fromInfo <= toInfo) // Can make use of an implicit conversion { var block = Result(to, Ex.Convert(input, to)); var lambda = Ex.Lambda(block, input); return(lambda); } else // Cannot make use of an implicit conversion, bounds must be checked. Precision might be lost. { var block = Ex.Condition( Ex.MakeBinary(Et.AndAlso, Ex.MakeBinary(Et.GreaterThanOrEqual, input, Ex.Convert(Ex.Constant(toInfo.MinValue), from)), Ex.MakeBinary(Et.LessThanOrEqual, input, Ex.Convert(Ex.Constant(toInfo.MaxValue), from))), Result(to, Ex.Convert(input, to)), NoResult(to)); var lambda = Ex.Lambda(block, input); return(lambda); } }
private LambdaExpression toDictLambda(Type from, Type to) { var valueType = recordCreator.GetValueType(to); var recType = typeof(IRecord <>).MakeGenericType(valueType); var set = recType.GetTypeInfo().GetDeclaredMethod(nameof(IRecord <object> .SetValue)); var input = Ex.Parameter(from, "input"); var tmp = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(valueType), "tmp"); var res = Ex.Parameter(typeof(IDictionary <,>).MakeGenericType(typeof(string), valueType), "res"); var rec = Ex.Parameter(recType, "rec"); var getters = GetReadablePropertiesForType(from); var converters = getters.Select(g => Ref.GetLambda(g.PropertyType, valueType)); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to)); var block = Ex.Block(new[] { tmp, res, rec }, Ex.Assign(res, Ex.New(GetParameterlessConstructor(to))), Ex.Assign(rec, recordCreator.Creator(to).ApplyTo(res)), Ex.IfThen(Ex.MakeBinary(ExpressionType.Equal, rec, Ex.Default(rec.Type)), Ex.Goto(end, NoResult(to))), Ex.Block(getters.Zip(converters, (g, c) => new { g, c }) .Select(x => Ex.Block( Ex.Assign(tmp, x.c.ApplyTo(Ex.Property(input, x.g))), Ex.IfThenElse(Ex.Property(tmp, nameof(IConversionResult.IsSuccessful)), Ex.Call(rec, set, Ex.Constant(x.g.Name), Ex.Property(tmp, nameof(IConversionResult.Result))), Ex.Goto(end, NoResult(to)))))), Ex.Label(end, Result(to, Ex.Convert(res, to)))); return(Ex.Lambda(block, input)); }
static GlyphRunFormatter() { var refType = typeof(CharacterBufferReference); _textFormattingMode = typeof(GlyphRun).GetField("_textFormattingMode", BindingFlags.NonPublic | BindingFlags.Instance); { var property = refType.GetProperty("CharacterBuffer", BindingFlags.NonPublic | BindingFlags.Instance); var param0 = Expr.Parameter(refType); var expr = Expr.Convert(Expr.Property(param0, property), typeof(IList <char>)); var lambda = Expr.Lambda <Func <CharacterBufferReference, IList <char> > >(expr, param0); getCharBuf = lambda.Compile(); } { var property = refType.GetProperty("OffsetToFirstChar", BindingFlags.NonPublic | BindingFlags.Instance); var param0 = Expr.Parameter(refType); var expr = Expr.Property(param0, property); var lambda = Expr.Lambda <Func <CharacterBufferReference, int> >(expr, param0); getCharOffset = lambda.Compile(); } { var ctor = typeof(TextBounds).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0]; var param0 = Expr.Parameter(typeof(Rect)); var expr = Expr.New(ctor, param0, Expr.Constant(FlowDirection.LeftToRight), Expr.Constant(null, typeof(IList <TextRunBounds>))); var lambda = Expr.Lambda <Func <Rect, TextBounds> >(expr, param0); makeBounds = lambda.Compile(); } }
private object CastResult(object result, Type targetType) { if (result == null || result == DependencyProperty.UnsetValue || result == System.Windows.Data.Binding.DoNothing || targetType == null || targetType == typeof(object)) { return(result); } if (targetType == typeof(string)) { return(result.ToString()); } Func <object, object> cast; if (!castFunctions.TryGetValue(targetType, out cast)) { ParameterExpression par = Expression.Parameter(typeof(object)); cast = Expression.Lambda <Func <object, object> >(Expression.Convert(Expression.Dynamic(Binder.Convert(CSharpBinderFlags.ConvertExplicit, targetType, typeof(object)), targetType, par), typeof(object)), par).Compile(); castFunctions.TryAdd(targetType, cast); } if (cast != null) { try { result = cast(result); } catch { castFunctions[targetType] = null; } } return(result); }
/// <summary> /// Returns node's value for the given context. /// </summary> /// <param name="context">Object to evaluate node against.</param> /// <param name="variables">Expression variables map.</param> /// <returns>Node's value.</returns> public object GetValue(object context, IDictionary <string, object> variables) { // todo: oczywiœcie ten lock jest z dupy... // lock (this) { if (_compiledExpression == null) { if (_lastEvaluationContext != null) { _lastEvaluationContext.Reuse(context, variables); } else { _lastEvaluationContext = new EvaluationContext(context, variables); } // todo: zapamiêtujemy zbudowane expression! // todo: zapamiêtujemy funkcjê, która dostaje na ryja obecta! z contextem! // todo: i go rzutuje! LExpression getContextExpression; var ctxParam = LExpression.Parameter(typeof(object), "context"); if (context == null) { getContextExpression = LExpression.Constant(null); } else { getContextExpression = LExpression.Convert(ctxParam, context.GetType()); } var getEvalContextExpression = LExpression.Parameter( typeof(EvaluationContext), "evalContext"); var exp = GetExpressionTreeIfPossible(getContextExpression, getEvalContextExpression); exp = LExpression.Convert(exp, typeof(object)); //var convExp = System.Linq.Expressions.Expression.Convert(expr, typeof(object)); Expression <Func <object, EvaluationContext, object> > lambda = LExpression.Lambda <Func <object, EvaluationContext, object> >(exp, ctxParam, getEvalContextExpression); // no i co dalej... jak // todo: co z lastEvaluationContext? mo¿e nie jest potrzebny? oto jest pytanie! // todo: mo¿emy go tutaj przekazaæ... albo po prostu utworzyæ w œrodku... // todo: pytanie, czy mo¿emy do na rz¹danie utworzyæ? kurde... raczej nie... _compiledExpression = lambda.Compile(); } return(_compiledExpression(context, _lastEvaluationContext)); // todo: jeœli siê coœ wyjeba³o albo null, to oczywiœcie wychodzimy i jedziemy star¹, woln¹ œcie¿k¹.... return(Get(context, _lastEvaluationContext)); } }
static Expression ToBool(DynamicMetaObject target) { if (target.LimitType == typeof(bool)) { return(Expr.Convert(target.Expression, typeof(bool))); } return(Expr.NotEqual(target.Expression, Expr.Constant(null))); }
public LambdaExpression CreateLambda(Type from, Type to) { var input = Ex.Parameter(from, "input"); var block = Result(to, Ex.Convert(input, to)); var lambda = Ex.Lambda(block, input); return(lambda); }
public override SysExpr ToExpression() { if (NodeType == ExpressionType.Convert) { return(SysExpr.Convert(Operand.ToExpression(), Type)); } throw new NotSupportedException("Cannot convert Expression to Expression of type " + NodeType); }
/// <summary> /// Creates a function that accepts 0 parameters and returns an untyped result /// </summary> /// <param name="Host">The declaring type instance, if applicable</param> /// <returns></returns> public Func <object> Func0(object Host = null) { var instance = Host != null?XPR.Constant(Host) : default(XPR); var result = XPR.Convert(XPR.Call(instance, this), typeof(object)); return(XPR.Lambda <Func <object> >(result).Compile()); }
private static Expression <Func <T, object> > ToLambda <T>(string propertyName) { var parameter = Expression.Parameter(typeof(T)); var property = Expression.Property(parameter, propertyName); var propAsObject = Expression.Convert(property, typeof(object)); return(Expression.Lambda <Func <T, object> >(propAsObject, parameter)); }
private static Func <PluginMetadata, object> MakeCreateFunc(Type type, string name) { // TODO: what do i want the visibiliy of Init methods to be? var ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance) .Select(c => (c, attr: c.GetCustomAttribute <InitAttribute>())) .NonNull(t => t.attr) .OrderByDescending(t => t.c.GetParameters().Length) .Select(t => t.c).ToArray(); if (ctors.Length > 1) { Logger.loader.Warn($"Plugin {name} has multiple [Init] constructors. Picking the one with the most parameters."); } bool usingDefaultCtor = false; var ctor = ctors.FirstOrDefault(); if (ctor == null) { // this is a normal case usingDefaultCtor = true; ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new InvalidOperationException($"{type.FullName} does not expose a public default constructor and has no constructors marked [Init]"); } } var initMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Select(m => (m, attr: m.GetCustomAttribute <InitAttribute>())) .NonNull(t => t.attr).Select(t => t.m).ToArray(); // verify that they don't have lifecycle attributes on them foreach (var method in initMethods) { var attrs = method.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false); if (attrs.Length != 0) { throw new InvalidOperationException($"Method {method} on {type.FullName} has both an [Init] attribute and a lifecycle attribute."); } } var metaParam = Expression.Parameter(typeof(PluginMetadata), "meta"); var objVar = ExpressionEx.Variable(type, "objVar"); var persistVar = ExpressionEx.Variable(typeof(object), "persistVar"); var createExpr = Expression.Lambda <Func <PluginMetadata, object> >( ExpressionEx.Block(new[] { objVar, persistVar }, initMethods .Select(m => PluginInitInjector.InjectedCallExpr(m.GetParameters(), metaParam, persistVar, es => Expression.Call(objVar, m, es))) .Prepend(ExpressionEx.Assign(objVar, usingDefaultCtor ? Expression.New(ctor) : PluginInitInjector.InjectedCallExpr(ctor.GetParameters(), metaParam, persistVar, es => Expression.New(ctor, es)))) .Append(Expression.Convert(objVar, typeof(object)))), metaParam); // TODO: since this new system will be doing a f**k load of compilation, maybe add FastExpressionCompiler return(createExpr.Compile()); }
/// <summary> /// Creates a function that accepts 3 untyped parameters and returns an untyped result /// </summary> /// <param name="Host">The declaring type instance, if applicable</param> /// <returns></returns> public Func <object, object, object, object> Func3(object Host = null) { var instance = Host != null?XPR.Constant(Host) : default; var callResult = XPR.Call(null, this, ArgumentExpressions); var result = XPR.Convert(callResult, typeof(object)); return(XPR.Lambda <Func <object, object, object, object> >(result, GetParameters(3)).Compile()); }
public void BinaryExpression_Power() { ExecuteBinaryExpr(Property.Id, id => { var pow = Expr.Convert(Expr.Power(Expr.Convert(id, typeof(double)), Expr.Constant(2.0)), typeof(int)); return(pow); }, ExpressionType.Power); }
public TExPI(Expression ex) : base(ex) { id = Ex.Field(ex, "id"); t = Ex.Field(ex, "t"); loc = Ex.Field(ex, "loc"); locx = Ex.Field(loc, "x"); locy = Ex.Field(loc, "y"); index = Ex.Field(ex, "index"); findex = Ex.Convert(index, ExUtils.tfloat); }
private Expression <Func <object, object> > ToExpression(Type type) { var parameter = LinqExpression.Parameter(typeof(object)); var castedParameter = LinqExpression.Convert(parameter, type); var jsonpathExpr = Root.ToExpression(castedParameter); var castedResult = LinqExpression.Convert(jsonpathExpr, typeof(object)); var lambda = LinqExpression.Lambda <Func <object, object> >(castedResult, parameter); return(lambda); }
protected TExPI(ExMode m, string?name) : base(m, name) { id = Ex.Field(ex, "id"); t = Ex.Field(ex, "t"); loc = Ex.Field(ex, "loc"); locx = Ex.Field(loc, "x"); locy = Ex.Field(loc, "y"); index = Ex.Field(ex, "index"); findex = Ex.Convert(index, ExUtils.tfloat); }
private static RuleGenerator /*!*/ CreateGetter(int index) { return(delegate(MetaObjectBuilder /*!*/ metaBuilder, CallArguments /*!*/ args, string /*!*/ name) { metaBuilder.Result = Ast.Call( Ast.Convert(args.TargetExpression, typeof(RubyStruct)), typeof(RubyStruct).GetMethod("GetValue"), Ast.Constant(index) ); }); }
static ExpressionBody CompileLogical(Func <ExpressionBody, ExpressionBody, ExpressionBody> apply, ExpressionBody lhs, ExpressionBody rhs) { return(LX.Convert( LX.New( typeof(ScalarValue).GetConstructor(new[] { typeof(object) }) !, LX.Convert(apply( LX.Call(CoerceToScalarBooleanMethod, lhs), LX.Call(CoerceToScalarBooleanMethod, rhs)), typeof(object))), typeof(LogEventPropertyValue))); }
/// <inheritdoc/> protected override IEnumerable <Act> Query(Expression <Func <Act, bool> > query, Guid queryId, int offset, int count, out int totalResults) { var typeReference = Expression.MakeBinary(ExpressionType.Equal, Expression.Convert(Expression.MakeMemberAccess(query.Parameters[0], typeof(Act).GetProperty(nameof(Act.ClassConceptKey))), typeof(Guid)), Expression.Constant(ActClassKeys.Condition)); var anyRef = this.CreateConceptSetFilter(ConceptSetKeys.AdverseEventActs, query.Parameters[0]); query = Expression.Lambda <Func <Act, bool> >(Expression.AndAlso(Expression.AndAlso(query.Body, anyRef), typeReference), query.Parameters); return(base.Query(query, queryId, offset, count, out totalResults)); }
public static Func <object, object> FieldGet(this Type type, string fieldName) { var param = Expression.Parameter(typeof(object), "arg"); var paramCast = Expression.Convert(param, type); var member = Expression.Field(paramCast, fieldName); var memberCast = Expression.Convert(member, typeof(object)); var lambda = Expression.Lambda(memberCast, param); return((Func <object, object>)lambda.Compile()); }
/// <summary> /// Creates a functor for converting an object of the specified type to DynamoDBEntry /// </summary> private static Func <object, DynamoDBEntry> GetToDynamoDbEntryConversionFunctor(Type valueType) { // parameter, that represents input value var valueParameter = Expression.Parameter(typeof(object)); if (valueType.IsPrimitive()) { // first converting to a valueType (or to int, if it's an enum) var primitiveConversionExp = Expression.Convert(valueParameter, valueType.BaseType == typeof(Enum) ? typeof(int) : valueType); // then to Primitive | Since AWSSDK 2.3.2.0, conversion to DynamoDbEntry type now yields object of internal type UnconvertedDynamoDBEntry which is not derived from Primitive thus breaking Linq2DynamoDb primitiveConversionExp = Expression.Convert(primitiveConversionExp, typeof(Primitive)); return((Func <object, DynamoDBEntry>)Expression.Lambda(primitiveConversionExp, valueParameter).Compile()); } // now trying to create a routine for converting a collection Type elementType = null; bool isListOrArray = false; if (valueType.IsArray) { elementType = valueType.GetElementType(); isListOrArray = true; } else if (valueType.ImplementsInterface(typeof(ICollection <>))) { elementType = valueType.GetGenericArguments()[0]; isListOrArray = true; } if (isListOrArray) { if ( (elementType == null) || (!elementType.IsPrimitive()) ) { var toDynamoDbListMethodInfo = ((Func <object, Type, DynamoDBList>)ToDynamoDbList).Method; var toDynamoDbConversionExp = Expression.Call(toDynamoDbListMethodInfo, valueParameter, Expression.Constant(elementType)); return((Func <object, DynamoDBEntry>)Expression.Lambda(toDynamoDbConversionExp, valueParameter).Compile()); //throw new InvalidCastException(string.Format("Cannot convert type {0} to DynamoDbEntry", valueType)); } var toPrimitiveListMethodInfo = ((Func <object, Type, PrimitiveList>)ToPrimitiveList).Method; var conversionExp = Expression.Call(toPrimitiveListMethodInfo, valueParameter, Expression.Constant(elementType)); return((Func <object, DynamoDBEntry>)Expression.Lambda(conversionExp, valueParameter).Compile()); } var documentConvertor = GetEntityToDocumentConvertorFunctor(valueType); return(documentConvertor); }
public Expression BuildExpression(IParseContext context, Expression expression) { var newExpr = expression.Convert(pi => { switch (pi.NodeType) { case ExpressionType.MemberAccess: { if (IsSubQuery(context, pi)) return BuildSubQuery(context, pi); if (IsServerSideOnly(pi) || PreferServerSide(pi)) return BuildSql(context, pi); var ctx = GetContext(context, pi); if (ctx != null) return ctx.BuildExpression(pi, 0); var ma = (MemberExpression)pi; var ex = ma.Expression; /* if (query.Sources.Length > 0) { var field = query.GetBaseField(lambda, ma); if (field != null) { if (field is QueryField.Column) return BuildField(ma, field, converter); if (field is QuerySource.SubQuery) return BuildSubQuerySource(ma, (QuerySource.SubQuery)field, converter); if (field is QueryField.ExprColumn) { var col = (QueryField.ExprColumn)field; return BuildNewExpression(lambda, col.QuerySource, col.Expr, converter); } if (field is QuerySource.Table) return BuildTable(ma, (QuerySource.Table)field, null, converter); if (field is QueryField.SubQueryColumn) return BuildSubQuerySource(ma, (QueryField.SubQueryColumn)field, converter); if (field is QueryField.GroupByColumn) return BuildGroupBy(ma, (QueryField.GroupByColumn)field, converter); if (field is QuerySource.SubQuerySourceColumn) return BuildSubQuerySourceColumn(pi, (QuerySource.SubQuerySourceColumn)field, converter); throw new InvalidOperationException(); } //if (ex.Expr == expr.Expr && query is QuerySource.Scalar && ex.NodeType == ExpressionType.Constant) // return BuildField(lambda, query, ma); } else { var field = GetField(lambda, ma, query); if (field != null) return BuildField(ma, field, converter/*i => i/); } */ if (ex != null && ex.NodeType == ExpressionType.Constant) { // field = localVariable // var c = _expressionAccessors[ex]; return Expression.MakeMemberAccess(Expression.Convert(c, ex.Type), ma.Member); } break; } case ExpressionType.Parameter: { if (pi == ParametersParam) break; var ctx = GetContext(context, pi); if (ctx != null) return ctx.BuildExpression(pi, 0); throw new NotImplementedException(); /* if (query.Lambda != null && query.Lambda.MethodInfo != null && query.Lambda.MethodInfo.Name == "Select" && query.Lambda.Parameters.Length == 2 && query.Lambda.Parameters[1] == pi) { return Expression.MakeMemberAccess(_contextParam, QueryCtx.Counter); } var field = query.GetBaseField(lambda, pi); if (field != null) { //Func<FieldIndex,FieldIndex> conv = i => converter(query.EnsureField(i.Field).Select(this)[0]); if (field is QuerySource.Table) return BuildTable(pi, (QuerySource.Table)field, null, converter); if (field is QuerySource.Scalar) { var source = (QuerySource)field; return BuildNewExpression(lambda, source, source.Lambda.Body, converter); } if (field is QuerySource.Expr) { var source = (QuerySource)field; return BuildQuerySourceExpr(query, source.Lambda.Body, converter); } if (field is QuerySource.GroupJoin) return BuildGroupJoin(pi, (QuerySource.GroupJoin)field, converter); if (field is QuerySource.SubQuery) return BuildSubQuerySource(pi, (QuerySource.SubQuery)field, converter); if (field is QuerySource.SubQuerySourceColumn) return BuildSubQuerySourceColumn(pi, (QuerySource.SubQuerySourceColumn)field, converter); throw new InvalidOperationException(); } //if (query.Lambda == null && query is QuerySource.SubQuerySourceColumn) //{ // return BuildSubQuerySourceColumn(pi, (QuerySource.SubQuerySourceColumn)query, converter); //} break; */ } case ExpressionType.Constant: { if (ExpressionHelper.IsConstant(pi.Type)) break; if (_expressionAccessors.ContainsKey(pi)) return Expression.Convert(_expressionAccessors[pi], pi.Type); throw new NotImplementedException(); /* if (query.Sources.Length == 0) { var field = GetField(lambda, pi, query); if (field != null) { var idx = field.Select(this); return BuildField(pi, field.GetExpressions(this)[0], idx.Select(i => converter(i).Index).ToArray()); } } if (query is QuerySource.Scalar && CurrentSql.Select.Columns.Count == 0 && expr == pi) return BuildField(lambda, query.BaseQuery, pi, converter); if (query is QuerySource.SubQuerySourceColumn) return BuildSubQuerySourceColumn(pi, (QuerySource.SubQuerySourceColumn)query, converter); return Expression.Convert(ExpressionAccessors[pi], pi.Type); */ } case ExpressionType.Coalesce: if (pi.Type == typeof(string) && MappingSchema.GetDefaultNullValue<string>() != null) return BuildSql(context, pi); if (CanBeTranslatedToSql(context, pi, true)) return BuildSql(context, pi); break; case ExpressionType.Conditional: if (CanBeTranslatedToSql(context, pi, true)) return BuildSql(context, pi); break; case ExpressionType.Call: { var ce = (MethodCallExpression)pi; var cm = ConvertMethod(ce); if (cm != null) if (ce.Method.GetCustomAttributes(typeof(MethodExpressionAttribute), true).Length != 0) return BuildExpression(context, cm); if (IsSubQuery(context, pi)) return BuildSubQuery(context, pi); if (IsServerSideOnly(pi) || PreferServerSide(pi)) return BuildSql(context, pi); } break; } if (EnforceServerSide(context)) { switch (pi.NodeType) { case ExpressionType.MemberInit: case ExpressionType.New: case ExpressionType.Convert: break; default: if (CanBeCompiled(pi)) break; return BuildSql(context, pi); } } return pi; }); return newExpr; }
internal static Expression ConvertValue(ITypeName typeName, Expression expr) { Type reflectionType = typeName.GetReflectionType(); if (reflectionType == null) { return Expression.Dynamic(PSDynamicConvertBinder.Get(), typeof(object), Expression.Call(CachedReflectionInfo.TypeOps_ResolveTypeName, Expression.Constant(typeName)), expr); } if (reflectionType.Equals(typeof(void))) { return Expression.Block(typeof(void), new Expression[] { expr }); } return expr.Convert(reflectionType); }
Expression IAssignableValue.SetValue(Compiler compiler, Expression rhs) { IEnumerable<PropertyInfo> enumerable; bool flag; if (this.VariablePath.IsVariable && this.VariablePath.UnqualifiedPath.Equals("null", StringComparison.OrdinalIgnoreCase)) { return rhs; } Type type = this.GetVariableType(compiler, out enumerable, out flag); Type type2 = rhs.Type; if ((flag && (type.Equals(typeof(object)) || type.Equals(typeof(PSObject)))) && (type2.Equals(typeof(object)) || type2.Equals(typeof(PSObject)))) { rhs = Expression.Dynamic(PSVariableAssignmentBinder.Get(), typeof(object), rhs); } rhs = rhs.Convert(type); if (!flag) { return Compiler.CallSetVariable(Expression.Constant(this.VariablePath), rhs, null); } Expression localVariablesParameter = compiler.LocalVariablesParameter; foreach (PropertyInfo info in enumerable) { localVariablesParameter = Expression.Property(localVariablesParameter, info); } return Expression.Assign(localVariablesParameter, rhs); }
Expression BuildSubQuery(IParseContext context, Expression expression) { if (expression.NodeType == ExpressionType.MemberAccess) { var ma = (MemberExpression)expression; if (ma.Expression != null) { switch (ma.Expression.NodeType) { case ExpressionType.Call : case ExpressionType.MemberAccess : case ExpressionType.Parameter : { var ctx = GetSubQuery(context, ma.Expression); var ex = expression.Convert(e => e == ma.Expression ? Expression.Constant(null, ma.Expression.Type) : e); var sql = ctx.ConvertToSql(ex, 0, ConvertFlags.Field); if (sql.Length != 1) throw new NotImplementedException(); //ctx.SqlQuery.Select.Columns.Clear(); ctx.SqlQuery.Select.Add(sql[0].Sql); var idx = context.SqlQuery.Select.Add(ctx.SqlQuery); return BuildSql(expression.Type, idx); } } } } var sequence = GetSubQuery(context, expression); return sequence.BuildExpression(null, 0); throw new NotImplementedException(); /* ParentQueries.Insert(0, new ParentQuery { Parent = query.BaseQuery, Parameter = query.Lambda.Parameters[0]}); var sql = CurrentSql; CurrentSql = new SqlQuery { ParentSql = sql }; var prev = _isSubQueryParsing; _isSubQueryParsing = true; var seq = ParseSequence(expr)[0]; _isSubQueryParsing = prev; if (seq.Fields.Count == 1 && CurrentSql.Select.Columns.Count == 0) seq.Fields[0].Select(this); var column = new QueryField.ExprColumn(query, CurrentSql, null); query.Fields.Add(column); var idx = column.Select(this); var result = BuildField(expr, column.GetExpressions(this)[0], idx.Select(i => converter(i).Index).ToArray()); CurrentSql = sql; ParentQueries.RemoveAt(0); ParsingTracer.DecIndentLevel(); return result; */ }
ISqlExpression ParseSubQuery(IParseContext context, Expression expression) { if (expression.NodeType == ExpressionType.MemberAccess) { var ma = (MemberExpression)expression; if (ma.Expression != null) { switch (ma.Expression.NodeType) { case ExpressionType.Call : case ExpressionType.MemberAccess : case ExpressionType.Parameter : { var ctx = GetSubQuery(context, ma.Expression); var ex = expression.Convert(e => e == ma.Expression ? Expression.Constant(null, ma.Expression.Type) : e); var sql = ctx.ConvertToSql(ex, 0, ConvertFlags.Field); if (sql.Length != 1) throw new NotImplementedException(); ctx.SqlQuery.Select.Add(sql[0].Sql); var idx = context.SqlQuery.Select.Add(ctx.SqlQuery); return context.SqlQuery.Select.Columns[idx]; } } } } var sequence = GetSubQuery(context, expression); /* if (expr.NodeType == ExpressionType.Call) { var call = (MethodCallExpression)expr; if (call.Method.Name == "Any" && (call.Method.DeclaringType == typeof(Queryable) || call.Method.DeclaringType == typeof(Enumerable))) return ((SqlQuery.Predicate.FuncLike) result.Where.SearchCondition.Conditions[0].Predicate).Function; } */ return sequence.SqlQuery; }
public Expression BuildExpression(IBuildContext context, Expression expression) { var newExpr = expression.Convert(pi => { switch (pi.NodeType) { case ExpressionType.MemberAccess: { if (IsServerSideOnly(pi) || PreferServerSide(pi)) return BuildSql(context, pi); var ma = (MemberExpression)pi; if (ConvertMember(ma.Member) != null) break; var ctx = GetContext(context, pi); if (ctx != null) return ctx.BuildExpression(pi, 0); var ex = ma.Expression; if (ex != null && ex.NodeType == ExpressionType.Constant) { // field = localVariable // var c = _expressionAccessors[ex]; return Expression.MakeMemberAccess(Expression.Convert(c, ex.Type), ma.Member); } break; } case ExpressionType.Parameter: { if (pi == ParametersParam) break; var ctx = GetContext(context, pi); if (ctx != null) return ctx.BuildExpression(pi, 0); throw new NotImplementedException(); } case ExpressionType.Constant: { if (ExpressionHelper.IsConstant(pi.Type)) break; if (_expressionAccessors.ContainsKey(pi)) return Expression.Convert(_expressionAccessors[pi], pi.Type); throw new NotImplementedException(); } case ExpressionType.Coalesce: if (pi.Type == typeof(string) && MappingSchema.GetDefaultNullValue<string>() != null) return BuildSql(context, pi); if (CanBeTranslatedToSql(context, ConvertExpression(pi), true)) return BuildSql(context, pi); break; case ExpressionType.Conditional: if (CanBeTranslatedToSql(context, ConvertExpression(pi), true)) return BuildSql(context, pi); break; case ExpressionType.Call: { var ce = (MethodCallExpression)pi; var cm = ConvertMethod(ce); if (cm != null) if (ce.Method.GetCustomAttributes(typeof(MethodExpressionAttribute), true).Length != 0) return BuildExpression(context, cm); if (IsSubQuery(context, ce)) return GetSubQuery(context, ce).BuildExpression(null, 0); if (IsServerSideOnly(pi) || PreferServerSide(pi)) return BuildSql(context, pi); } break; } if (EnforceServerSide(context)) { switch (pi.NodeType) { case ExpressionType.MemberInit: case ExpressionType.New: case ExpressionType.Convert: break; default: if (CanBeCompiled(pi)) break; return BuildSql(context, pi); } } return pi; }); return newExpr; }
internal static Expression ConvertValue(TypeConstraintAst typeConstraint, Expression expr) { var typeName = typeConstraint.TypeName; var toType = typeName.GetReflectionType(); if (toType != null) { if (toType == typeof(void)) { return Expression.Block(typeof(void), expr); } return expr.Convert(toType); } // typeName can't be resolved at compile time, so defer resolution until runtime. return DynamicExpression.Dynamic(PSDynamicConvertBinder.Get(), typeof(object), Expression.Call(CachedReflectionInfo.TypeOps_ResolveTypeName, Expression.Constant(typeName), Expression.Constant(typeName.Extent)), expr); }