protected override object VisitIf(If I) { string name = target.LabelName(); LinqExprs.LabelTarget _else = LinqExpr.Label("if_" + name + "_else"); LinqExprs.LabelTarget end = LinqExpr.Label("if_" + name + "_end"); // Check the condition, exit if necessary. target.Add(LinqExpr.IfThen(LinqExpr.Not(target.Compile(I.Condition)), LinqExpr.Goto(_else))); // Execute true code. target.PushScope(); Visit(I.True); target.PopScope(); target.Add(LinqExpr.Goto(end)); // Execute false code. target.Add(LinqExpr.Label(_else)); target.PushScope(); Visit(I.False); target.PopScope(); // Exit point. target.Add(LinqExpr.Label(end)); return(null); }
/// <summary> /// Generate a while loop with the given code generator functions. /// </summary> /// <param name="Condition"></param> /// <param name="Body"></param> public void While( LinqExpr Condition, Action <LinqExpr, LinqExpr> Body) { string name = LabelName(); LinqExprs.LabelTarget begin = LinqExpr.Label("while_" + name + "_begin"); LinqExprs.LabelTarget end = LinqExpr.Label("while_" + name + "_end"); PushScope(); // Check the condition, exit if necessary. code.Add(LinqExpr.Label(begin)); code.Add(LinqExpr.IfThen(LinqExpr.Not(Condition), LinqExpr.Goto(end))); // Generate the body code. Body(LinqExpr.Goto(end), LinqExpr.Goto(begin)); // Loop. code.Add(LinqExpr.Goto(begin)); // Exit label. code.Add(LinqExpr.Label(end)); PopScope(); }
protected override object VisitWhile(While W) { string name = target.LabelName(); LinqExprs.LabelTarget begin = LinqExpr.Label("while_" + name + "_begin"); LinqExprs.LabelTarget end = LinqExpr.Label("while_" + name + "_end"); loops.Push(new Loop(LinqExpr.Goto(end), LinqExpr.Goto(begin))); target.PushScope(); // Check the condition, exit if necessary. target.Add(LinqExpr.Label(begin)); target.Add(LinqExpr.IfThen(LinqExpr.Not(target.Compile(W.Condition)), LinqExpr.Goto(end))); // Generate the body target. Visit(W.Body); // Loop. target.Add(LinqExpr.Goto(begin)); // Exit label. target.Add(LinqExpr.Label(end)); loops.Pop(); target.PopScope(); return(null); }
public LambdaExpression CreateLambda(Type from, Type to) { var toParameters = to.GetTypeInfo().GenericTypeArguments; var tupa = toParameters.Length; var input = Ex.Parameter(from, "input"); var converters = toParameters.Select(p => Ref.GetLambda(typeof(string), p)).ToArray(); var res = toParameters.Select(p => Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p))).ToArray(); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end"); var indexer = typeof(string[]).GetTypeInfo().GetDeclaredProperty("Item"); var split = Ex.Parameter(typeof(string[]), "split"); var conversion = Ex.Block(converters.Select((c, i) => Ex.Block( Ex.Assign(res[i], c.ApplyTo(Ex.MakeIndex(split, indexer, new[] { Ex.MakeBinary(Et.Add, Ex.Constant(i), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))) }))), Ex.IfThen(Ex.Not(Ex.Property(res[i], nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to)))))); var block = Ex.Block(new[] { split }, Ex.Assign(split, Ex.Call(input, nameof(string.Split), Type.EmptyTypes, _separator)), Ex.Condition(Ex.MakeBinary(Et.LessThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)), NoResult(to), Ex.Block(res, Ex.IfThen(Ex.MakeBinary(Et.GreaterThan, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa)), Ex.Assign(Ex.ArrayAccess(split, Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))), Ex.Call(typeof(string), nameof(string.Join), Type.EmptyTypes, _separatorString, Ex.Call(typeof(Enumerable), nameof(Enumerable.Take), new[] { typeof(string) }, split, Ex.MakeBinary(Et.Add, Ex.Constant(1), Ex.MakeBinary(Et.Subtract, Ex.Property(split, nameof(Array.Length)), Ex.Constant(tupa))))))), conversion, Ex.Label(end, Result(to, Ex.Call(Creator(to), res.Select(r => Ex.Property(r, nameof(IConversionResult.Result))))))))); var lambda = Ex.Lambda(block, input); return(lambda); }
public void If( LinqExpr Condition, Action True, Action False) { string name = LabelName(); LinqExprs.LabelTarget _else = LinqExpr.Label("if_" + name + "_else"); LinqExprs.LabelTarget end = LinqExpr.Label("if_" + name + "_end"); // Check the condition, exit if necessary. code.Add(LinqExpr.IfThen(LinqExpr.Not(Condition), LinqExpr.Goto(_else))); // Execute true code. PushScope(); True(); PopScope(); code.Add(LinqExpr.Goto(end)); // Execute false code. code.Add(LinqExpr.Label(_else)); PushScope(); False(); PopScope(); // Exit point. code.Add(LinqExpr.Label(end)); }
protected override object VisitFor(For F) { target.PushScope(); // Generate the loop header code. Visit(F.Init); string name = target.LabelName(); LinqExprs.LabelTarget begin = LinqExpr.Label("for_" + name + "_begin"); LinqExprs.LabelTarget end = LinqExpr.Label("for_" + name + "_end"); loops.Push(new Loop(LinqExpr.Goto(end), LinqExpr.Goto(begin))); // Check the condition, exit if necessary. target.Add(LinqExpr.Label(begin)); target.Add(LinqExpr.IfThen(LinqExpr.Not(target.Compile(F.Condition)), LinqExpr.Goto(end))); // Generate the body code. Visit(F.Body); // Generate the step code. Visit(F.Step); target.Add(LinqExpr.Goto(begin)); // Exit point. target.Add(LinqExpr.Label(end)); loops.Pop(); target.PopScope(); return(null); }
/// <summary> /// Generate a for loop with the given code generator functions. /// </summary> /// <param name="Init"></param> /// <param name="Condition"></param> /// <param name="Step"></param> /// <param name="Body"></param> public void For( Action Init, LinqExpr Condition, Action Step, Action <LinqExpr, LinqExpr> Body) { PushScope(); // Generate the loop header code. Init(); string name = LabelName(); LinqExprs.LabelTarget begin = LinqExpr.Label("for_" + name + "_begin"); LinqExprs.LabelTarget end = LinqExpr.Label("for_" + name + "_end"); // Check the condition, exit if necessary. code.Add(LinqExpr.Label(begin)); code.Add(LinqExpr.IfThen(LinqExpr.Not(Condition), LinqExpr.Goto(end))); // Generate the body code. Body(LinqExpr.Goto(end), LinqExpr.Goto(begin)); // Generate the step code. Step(); code.Add(LinqExpr.Goto(begin)); // Exit point. code.Add(LinqExpr.Label(end)); PopScope(); }
public static ExTP LNearestEnemy() => b => { var loc = new TExV2(); return(Ex.Block(new ParameterExpression[] { loc }, Ex.IfThen(Ex.Not(Enemy.findNearest.Of(b.loc, loc)), loc.Is(Ex.Constant(new Vector2(0f, 50f))) ), loc )); };
public static ISpecification <T> Not <T>(this ISpecification <T> specification) where T : class { var not = Expression.Not(ExtractCondition <T>(specification.Expression).Body); var queryable = CreateQueryable <T>().Where(Expression.Lambda <Func <T, bool> >(not, ExtractCondition <T>(specification.Expression).Parameters)); queryable = AddOrdering(queryable, specification.Expression, false); queryable = AddPaging(queryable, specification.Expression, false); return(new Specification <T>(queryable.Expression)); }
private static Ex enumeratorConversion(Type to, Ex enumerator, Type eType, LambdaExpression[] converters, Ex[] res, System.Linq.Expressions.LabelTarget end) { return(Ex.Block(res.Zip(converters, (r, con) => Ex.Block( Ex.IfThenElse( enumerator.Type.GetTypeInfo().GetDeclaredMethod(nameof(IEnumerator.MoveNext)) == null ? Ex.Call(Ex.Convert(enumerator, typeof(IEnumerator)), nameof(IEnumerator.MoveNext), Type.EmptyTypes) : Ex.Call(enumerator, enumerator.Type.GetTypeInfo().GetDeclaredMethod(nameof(IEnumerator.MoveNext))), Ex.Assign(r, con.ApplyTo(Ex.Property(enumerator, nameof(IEnumerator.Current)))), Ex.Goto(end, NoResult(to))), Ex.IfThen(Ex.Not(Ex.Property(r, nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to))))))); }
public static Ex DictSafeGet(this Ex dict, Ex key, string err) { return(Ex.Block( Ex.IfThen(Ex.Not(ExUtils.DictContains(dict, key)), Ex.Throw(Ex.Constant(new Exception(err)))), dict.DictGet(key) )); /* * return Ex.Condition(ExUtils.DictContains<K, V>(dict, key), dict.DictGet(key), Ex.Block( * Ex.Throw(Ex.Constant(new Exception(err))), * dict.DictGet(key) * ));*/ }
private UnaryExpression UnaryExpression( ExpressionType nodeType, System.Type type, JObject obj) { var operand = this.Prop(obj, "operand", this.Expression); var method = this.Prop(obj, "method", this.Method); switch (nodeType) { case ExpressionType.ArrayLength: return(Expr.ArrayLength(operand)); case ExpressionType.Convert: return(Expr.Convert(operand, type, method)); case ExpressionType.ConvertChecked: return(Expr.ConvertChecked(operand, type, method)); case ExpressionType.Decrement: return(Expr.Decrement(operand, method)); case ExpressionType.Increment: return(Expr.Increment(operand, method)); case ExpressionType.IsFalse: return(Expr.IsFalse(operand, method)); case ExpressionType.IsTrue: return(Expr.IsTrue(operand, method)); case ExpressionType.Negate: return(Expr.Negate(operand, method)); case ExpressionType.NegateChecked: return(Expr.NegateChecked(operand, method)); case ExpressionType.Not: return(Expr.Not(operand, method)); case ExpressionType.OnesComplement: return(Expr.OnesComplement(operand, method)); case ExpressionType.PostDecrementAssign: return(Expr.PostDecrementAssign(operand, method)); case ExpressionType.PostIncrementAssign: return(Expr.PostIncrementAssign(operand, method)); case ExpressionType.PreDecrementAssign: return(Expr.PreDecrementAssign(operand, method)); case ExpressionType.PreIncrementAssign: return(Expr.PreIncrementAssign(operand, method)); case ExpressionType.Quote: return(Expr.Quote(operand)); case ExpressionType.Throw: return(Expr.Throw(operand, type)); case ExpressionType.TypeAs: return(Expr.TypeAs(operand, type)); case ExpressionType.UnaryPlus: return(Expr.UnaryPlus(operand, method)); case ExpressionType.Unbox: return(Expr.Unbox(operand, type)); default: throw new NotSupportedException(); } }
private LambdaExpression constructionLambda(Type from, Type to) { var valueType = recordCreator.GetValueType(from); var recType = typeof(IRecord <>).MakeGenericType(valueType); var tryGet = recType.GetTypeInfo().GetDeclaredMethod(nameof(IRecord <object> .TryGetValue)); var input = Ex.Parameter(from, "input"); var rec = Ex.Parameter(recType, "rec"); var ctor = GetConstructorForType(to); var tmp = Ex.Parameter(valueType, "tmp"); var pars = ctor.GetParameters().Select((p, i) => new { Converter = Ref.GetLambda(valueType, p.ParameterType), Var = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p.ParameterType), p.Name), Type = p.ParameterType, Optional = p.GetCustomAttributes <OptionalAttribute>().Any(), Default = p.HasDefaultValue ? p.DefaultValue : p.ParameterType.GetTypeInfo().IsValueType ? Activator.CreateInstance(p.ParameterType) : null }).ToArray(); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end"); var block = Ex.Block(new[] { rec }.Concat(pars.Select(x => x.Var)), Ex.Assign(rec, recordCreator.Creator(from).ApplyTo(input)), Ex.Block(new[] { tmp }, pars .Select(x => x.Optional ? Ex.Block( Ex.IfThenElse( Ex.MakeBinary(ExpressionType.OrElse, Ex.Call(rec, tryGet, Ex.Constant(x.Var.Name), tmp), Ex.Call(rec, tryGet, Ex.Constant(ToPascalCase(x.Var.Name)), tmp)), Ex.Block( Ex.Assign(x.Var, x.Converter.ApplyTo(tmp)), Ex.IfThen(Ex.Not(Ex.Property(x.Var, nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to)))), Ex.Assign(x.Var, Result(x.Type, Ex.Constant(x.Default, x.Type))))) : Ex.Block( Ex.IfThen(Ex.Not(Ex.Call(rec, tryGet, Ex.Constant(x.Var.Name), tmp)), Ex.IfThen(Ex.Not(Ex.Call(rec, tryGet, Ex.Constant(ToPascalCase(x.Var.Name)), tmp)), Ex.Goto(end, NoResult(to)))), Ex.Assign(x.Var, x.Converter.ApplyTo(tmp)), Ex.IfThen(Ex.Not(Ex.Property(x.Var, nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to)))))), Ex.Label(end, Result(to, Ex.New(ctor, pars.Select(p => Ex.Property(p.Var, nameof(IConversionResult.Result))))))); return(Ex.Lambda(block, input)); }
private LambdaExpression createForList(Type from, Type to) { var cType = (from i in @from.GetTypeInfo().ImplementedInterfaces.Concat(new[] { @from }) where i.GetTypeInfo().IsInterface && i.GenericTypeArguments.Length == 1 && i.GetGenericTypeDefinition() == typeof(IReadOnlyList <>) select i.GenericTypeArguments[0]).SingleOrDefault(); if (cType == null) { return(null); } var indexer = typeof(IReadOnlyList <>).MakeGenericType(cType).GetTypeInfo().GetDeclaredProperty("Item"); var count = typeof(IReadOnlyCollection <>).MakeGenericType(cType).GetTypeInfo().GetDeclaredProperty(nameof(IReadOnlyCollection <object> .Count)); var toParameters = to.GetTypeInfo().GenericTypeArguments; var input = Ex.Parameter(from, "input"); var converters = toParameters.Select(p => Ref.GetLambda(cType, p)).ToArray(); var res = toParameters.Select(p => Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(p))).ToArray(); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end"); var conversion = Ex.Block(converters.Select((c, i) => Ex.Block( Ex.Assign(res[i], c.ApplyTo(Ex.MakeIndex(input, indexer, new[] { Ex.Constant(i) }))), Ex.IfThen(Ex.Not(Ex.Property(res[i], nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to)))))); var block = Ex.Block(res, Ex.IfThen( Ex.MakeBinary(Et.LessThan, Ex.Property(input, count), Ex.Constant(toParameters.Length)), Ex.Goto(end, NoResult(to))), conversion, Ex.Label(end, Result(to, Ex.Call(Creator(to), res.Select(r => Ex.Property(r, nameof(IConversionResult.Result))))))); var lambda = Ex.Lambda(block, input); return(lambda); }
private Exp MakeUnary(CompilerState state, Node node) { if (state == null) { throw new Exception(); } if (node == null) { throw new Exception(); } var data = node.Token.Data as Tokenizing.OperatorData; if (data == null) { throw new Exception(); } if (node.Children.Count != 1) { throw new Exception(); } if (data.Operator == Operator.Minus) { var value = Make(state, node.Children[0]); return(Exp.Negate(value)); } if (data.Operator == Operator.LogicalNot) { var value = Make(state, node.Children[0]); return(Exp.Not(ToBoolean(value))); } throw new Exception(); }
public LambdaExpression CreateLambda(Type from, Type to) { var input = Ex.Parameter(from, "input"); var eType = to.GetElementType(); var res = Ex.Parameter(typeof(ConversionResult <>).MakeGenericType(eType).MakeArrayType(), "res"); var end = Ex.Label(typeof(ConversionResult <>).MakeGenericType(to), "end"); var fromParameters = from.GetTypeInfo().GenericTypeArguments; var converters = fromParameters.Select(t => new { Lambda = Ref.GetLambda(t, eType), Input = t }).ToArray(); var block = Ex.Block(new[] { res }, Ex.Assign(res, Ex.NewArrayBounds(typeof(ConversionResult <>).MakeGenericType(eType), Ex.Constant(fromParameters.Length))), Ex.Block(converters.Select((con, i) => Ex.Block( Ex.Assign(Ex.ArrayAccess(res, Ex.Constant(i)), con.Lambda.ApplyTo(Ex.PropertyOrField(input, $"Item{i + 1}"))), Ex.IfThen(Ex.Not(Ex.Property(Ex.ArrayIndex(res, Ex.Constant(i)), nameof(IConversionResult.IsSuccessful))), Ex.Goto(end, NoResult(to)))))), Ex.Label(end, Result(to, Ex.NewArrayInit(eType, Enumerable.Range(0, fromParameters.Length) .Select(idx => Ex.Property(Ex.ArrayIndex(res, Ex.Constant(idx)), nameof(IConversionResult.Result))))))); var lambda = Ex.Lambda(block, input); return(lambda); }
/// <summary> /// Negates the predicate. /// </summary> public static Expression <Func <T, bool> > Not <T>(this Expression <Func <T, bool> > expression) { var negated = Expression.Not(expression.Body); return(Expression.Lambda <Func <T, bool> >(negated, expression.Parameters)); }
/// <summary> /// Creates <see cref="ICriterion" /> for a comparison between a value and a projection. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <param name="value"> /// The value. /// </param> /// <param name="type"> /// The comparison type. /// </param> /// <param name="context"> /// The helper context. /// </param> /// <param name="overTurned"> /// Indicates whether the comparison has been reversed to simplify other code. /// </param> /// <returns> /// The created <see cref="ICriterion" />. /// </returns> /// <exception cref="NotSupportedException"> /// The <see cref="Expression" /> could not be resolved as it may contain unsupported features or similar. /// </exception> public static ICriterion GetProjectionValueCriterion ( Expression expression, object value, ExpressionType type, HelperContext context, bool overTurned ) { if (overTurned) { switch (type) { case ExpressionType.GreaterThan: type = ExpressionType.LessThan; break; case ExpressionType.GreaterThanOrEqual: type = ExpressionType.LessThanOrEqual; break; case ExpressionType.LessThan: type = ExpressionType.GreaterThan; break; case ExpressionType.LessThanOrEqual: type = ExpressionType.GreaterThanOrEqual; break; } } IProjection projection = ProjectionHelper.GetProjection(expression, context); switch (type) { case ExpressionType.Equal: if (value == null) { return(Restrictions.IsNull(projection)); } if (value is bool) { return(GetCriterion((bool)value ? expression : Expression.Not(expression), context)); } return(Restrictions.Eq(projection, value)); case ExpressionType.NotEqual: if (value == null) { return(Restrictions.IsNotNull(projection)); } if (value is bool) { return(GetCriterion(!(bool)value ? expression : Expression.Not(expression), context)); } return(Restrictions.Not(Restrictions.Eq(projection, value))); case ExpressionType.GreaterThan: return(Restrictions.Gt(projection, value)); case ExpressionType.GreaterThanOrEqual: return(Restrictions.Ge(projection, value)); case ExpressionType.LessThan: return(Restrictions.Lt(projection, value)); case ExpressionType.LessThanOrEqual: return(Restrictions.Le(projection, value)); default: throw new NotSupportedException ( "the expression contains unsupported features, please revise your code" ); } }
public static Expression Not(Expression arg) { return(new Expression(LinqExpression.Not(arg))); }
private static UnaryExpression NotContainsExpression(ParameterExpression parameter, string propertyName, object value) { var expression = ContainsExpression(parameter, propertyName, value); return(SystemExpression.Not(expression)); }
/// <summary> /// /// </summary> /// <returns></returns> protected override Expression <Func <TEntity, bool> > CreateExpression() { return(Expression_.Lambda <Func <TEntity, bool> >(Expression_.Not(_OriginalCriteria.Body), _OriginalCriteria.Parameters.Single())); }