public void AndIsShortcircuit() { IExpression falseexpr = new ConstantExpression(false); IExpression dividebyzero = new BinaryOperatorExpression(new ConstantExpression(1), new ConstantExpression(0), BinaryOperator.Divide); Assert.IsFalse((bool)(new BooleanExpression(falseexpr, dividebyzero, BooleanOperator.And)).Evaluate(null)); }
public Node Parse() { Expression curExpr = null; for (; ; ) { _tokens.MoveNext(); Token t = _tokens.Current; switch (t.Kind) { case TokenKinds.EOF: return curExpr; case TokenKinds.Operator: if (curExpr == null) { throw new SyntaxErrorException("expected value before operator"); } curExpr = ActionExpression.Operator(((OperatorToken)t).DlrOperator, curExpr, (Expression)Parse()); break; case TokenKinds.Constant: curExpr = new ConstantExpression(((ConstantToken)t).Value); break; } } }
public void OrIsShortcircuit() { IExpression trueexpr = new ConstantExpression(true); IExpression dividebyzero = new BinaryOperatorExpression(new ConstantExpression(1), new ConstantExpression(0), BinaryOperator.Divide); Assert.IsTrue((bool)(new BooleanExpression(trueexpr, dividebyzero, BooleanOperator.Or)).Evaluate(null)); }
public void CreateNotExpression() { IExpression trueexpr = new ConstantExpression(true); NotExpression expression = new NotExpression(trueexpr); Assert.AreEqual(trueexpr, expression.Expression); }
public void EvaluateNotExpression() { IExpression trueexpr = new ConstantExpression(true); IExpression falseexpr = new ConstantExpression(false); Assert.IsFalse((bool)(new NotExpression(trueexpr)).Evaluate(null)); Assert.IsTrue((bool)(new NotExpression(falseexpr)).Evaluate(null)); }
public void SetVariable() { IExpression expression = new ConstantExpression(1); BindingEnvironment environment = new BindingEnvironment(); ICommand command = new SetCommand("spam", expression); command.Execute(environment); Assert.AreEqual(1, environment.GetValue("spam")); }
public void EvaluateOr() { IExpression trueexpr = new ConstantExpression(true); IExpression falseexpr = new ConstantExpression(false); Assert.IsTrue((bool)(new BooleanExpression(trueexpr, trueexpr, BooleanOperator.Or)).Evaluate(null)); Assert.IsTrue((bool)(new BooleanExpression(trueexpr, falseexpr, BooleanOperator.Or)).Evaluate(null)); Assert.IsTrue((bool)(new BooleanExpression(falseexpr, trueexpr, BooleanOperator.Or)).Evaluate(null)); Assert.IsFalse((bool)(new BooleanExpression(falseexpr, falseexpr, BooleanOperator.Or)).Evaluate(null)); }
public void CreateBooleanExpression() { IExpression trueexpr = new ConstantExpression(true); IExpression falseexpr = new ConstantExpression(false); BooleanExpression expression = new BooleanExpression(trueexpr, falseexpr, BooleanOperator.Or); Assert.AreEqual(trueexpr, expression.Left); Assert.AreEqual(falseexpr, expression.Right); Assert.AreEqual(BooleanOperator.Or, expression.Operation); }
public void ExecuteSetIndexCommandOnList() { var list = new List<object>() { 1, 2, 2 }; IExpression targetExpression = new ConstantExpression(list); IExpression indexExpression = new ConstantExpression(2); IExpression valueExpression = new ConstantExpression(3); var command = new SetIndexCommand(targetExpression, indexExpression, valueExpression); command.Execute(null); Assert.AreEqual(3, list[2]); }
public void CreateSetIndexCommand() { IExpression targetExpression = new ConstantExpression(1); IExpression indexExpression = new ConstantExpression(2); IExpression valueExpression = new ConstantExpression(3); var command = new SetIndexCommand(targetExpression, indexExpression, valueExpression); Assert.AreEqual(targetExpression, command.TargetExpression); Assert.AreEqual(indexExpression, command.IndexExpression); Assert.AreEqual(valueExpression, command.Expression); }
public void ExecuteSetIndexCommandOnArray() { var array = new object[] { 1, 2, 2 }; IExpression targetExpression = new ConstantExpression(array); IExpression indexExpression = new ConstantExpression(2); IExpression valueExpression = new ConstantExpression(3); var command = new SetIndexCommand(targetExpression, indexExpression, valueExpression); command.Execute(null); Assert.AreEqual(3, array[2]); }
public void AConstant_ShouldReturnTheConstantValue() { // Arrange var expectedValue = 3; var sut = new ConstantExpression(expectedValue); // Act var actual = sut.Eval(); // Assert Assert.AreEqual(expectedValue, actual); }
public void CreateSetCommand() { IExpression expression = new ConstantExpression("bar"); SetCommand command = new SetCommand("foo", expression); Assert.IsNotNull(command); Assert.IsNotNull(command.Target); Assert.IsNotNull(command.Expression); Assert.AreEqual("foo", command.Target); Assert.AreEqual(expression, command.Expression); }
public void ExecuteSetIndexCommandOnDictionary() { var dictionary = new Hashtable(); IExpression targetExpression = new ConstantExpression(dictionary); IExpression indexExpression = new ConstantExpression("foo"); IExpression valueExpression = new ConstantExpression("bar"); var command = new SetIndexCommand(targetExpression, indexExpression, valueExpression); command.Execute(null); Assert.AreEqual("bar", dictionary["foo"]); }
/// <summary> /// Performs reverse-mode (adjoint) automatic differentiation /// </summary> /// <param name="builder"></param> /// <param name="dependentVariable"></param> /// <param name="independentVariables"></param> public static void Differentiate(BlockExpressionBuilder builder, out IList<Expression> derivativeExpressions, VectorParameterExpression dependentVariable, params VectorParameterExpression[] independentVariables) { if (independentVariables.Length == 0) { derivativeExpressions = null; return; } var block = builder.ToBlock(); // change the numbering of variables; arguments first, then locals List<int>[] jLookup; Function[] f; // we want a list of functions which can be unary or binary (in principle high order if it makes sense) and a look-up // each function is associated with a parameter, which is either an argument or a local // for each function index we return a list of the indices of the functions that reference the parameter GetFunctions(block, out f, out jLookup); int N = dependentVariable.Index; bool[] derivativeRequired; int[] derivativeExpressionIndex; IdentifyNeccesaryDerivatives(N, jLookup, independentVariables, out derivativeRequired, out derivativeExpressionIndex); // the list of operations needed to calculate the derivatives (*all* derivatives) derivativeExpressions = new Expression[independentVariables.Length]; var dxNdx = new Expression[N + 1]; dxNdx[N] = new ConstantExpression<double>(1.0); for (int i = N - 1; i >= 0; i--) { if (!derivativeRequired[i]) continue; // dxN / dxi // need to find all operation indices j such that p(j) contains i // that is, all functions that have xi as an argument (these must therefore have a higher index than i) VectorParameterExpression total = new ConstantExpression<double>(0); var xi = f[i].Parameter; //need sum of dfj/dxi dXN/dxj foreach (var j in jLookup[i]) { var fj = f[j]; var dfjdxi = Differentiate(fj, xi, builder); // dfj/dxi var dXNdxj = dxNdx[j]; // dXN/dxj var product = builder.AddProductExpression(dfjdxi, dXNdxj); total = builder.AddAdditionExpression(total, product); } dxNdx[i] = total; int targetIndex = derivativeExpressionIndex[i]; if (targetIndex != -1) derivativeExpressions[targetIndex] = total; } }
/// <summary> /// Adds the specified constant expression. /// </summary> /// <param name="constantExpression">The constant expression.</param> /// <param name="exponent">The exponent.</param> public void Add(ConstantExpression constantExpression, double exponent) { var additionalConstant = Math.Pow(constantExpression.Constant, exponent); if (this.constantFlatIdentifierRepresentation == null) { this.constantFlatIdentifierRepresentation = new ConstantFlatIdentifierRepresentation(additionalConstant); this.additionalCount++; } else { this.constantFlatIdentifierRepresentation = new ConstantFlatIdentifierRepresentation( this.constantFlatIdentifierRepresentation.Constant * additionalConstant); } }
static void Main(string[] args) { IArithmeticVisitor visitor = new ConsoleArithmeticVisitor(); IArithmeticExpression leftInnerNode = new ConstantExpression(39); IArithmeticExpression rightInnerNode = new ConstantExpression(13); IArithmeticExpression leftNode = new ConstantExpression(15); IArithmeticExpression rightNode = new SubtractionExpression(leftInnerNode, rightInnerNode); IArithmeticExpression rootNode = new MultiplicationExpression(leftNode, new BracketsExpression(rightNode)); rootNode.Accept(visitor); Console.WriteLine(); }
protected override Expression VisitConstant(ConstantExpression c) { return base.VisitConstant(c); }
public IQueryable <Product> SetWhere(IQueryable <Product> source) { // Queries if (queryParams.Queries != null && queryParams.Queries.Count() > 0) { ParameterExpression product = Expression.Parameter(typeof(Product)); BinaryExpression GetQueries(IEnumerable <Query> queries) { List <BinaryExpression> left = new List <BinaryExpression>(); BinaryExpression right = null; foreach (Query query in queries) { // Auto if (query.QueryType == QueryType.Auto) { // Browsed Products if (query.IntValue == 1) { if (queryParams.Cookies == null || queryParams.Cookies.Count(x => x.Key == "browse") == 0) { continue; } string browseCookie = queryParams.Cookies.Where(x => x.Key == "browse").Select(x => x.Value).SingleOrDefault(); if (browseCookie == null) { continue; } List <int> productIds = browseCookie.Split(',').Select(x => Int32.Parse(x)).ToList(); PropertyInfo productProperty = typeof(Product).GetProperty("Id"); MemberExpression productId = Expression.Property(product, productProperty); ConstantExpression values = Expression.Constant(productIds); MethodInfo method = productIds.GetType().GetMethod("Contains"); MethodCallExpression call = Expression.Call(values, method, productId); right = Expression.Equal(call, Expression.Constant(true)); } // Related products else if (query.IntValue == 2 && queryParams.ProductId > 0) { PropertyInfo nicheProperty = typeof(Product).GetProperty("NicheId"); PropertyInfo idProperty = typeof(Product).GetProperty("Id"); MemberExpression id = Expression.Property(product, idProperty); ConstantExpression productId = Expression.Constant(queryParams.ProductId); MemberExpression nicheId = Expression.Property(product, nicheProperty); ConstantExpression value = Expression.Constant(query.IntValues[0]); right = Expression.AndAlso(Expression.Equal(nicheId, value), Expression.NotEqual(id, productId)); } } // Category else if (query.QueryType == QueryType.Category) { PropertyInfo categoryProperty1 = typeof(Product).GetProperty("Niche"); PropertyInfo categoryProperty2 = categoryProperty1.PropertyType.GetProperty("Category"); PropertyInfo categoryProperty3 = categoryProperty2.PropertyType.GetProperty("Id"); MemberExpression niche = Expression.Property(product, categoryProperty1); MemberExpression niche_Category = Expression.Property(niche, categoryProperty2); MemberExpression niche_Category_Id = Expression.Property(niche_Category, categoryProperty3); ConstantExpression value = Expression.Constant(query.IntValue); right = Expression.Equal(niche_Category_Id, value); } // Niche else if (query.QueryType == QueryType.Niche) { if (query.IntValue > 0) { PropertyInfo nicheProperty = typeof(Product).GetProperty("NicheId"); MemberExpression nicheId = Expression.Property(product, nicheProperty); ConstantExpression value = Expression.Constant(query.IntValue); right = Expression.Equal(nicheId, value); } else { PropertyInfo categoryProperty1 = typeof(Product).GetProperty("Niche"); PropertyInfo categoryProperty2 = categoryProperty1.PropertyType.GetProperty("UrlId"); MemberExpression niche = Expression.Property(product, categoryProperty1); MemberExpression niche_Url_Id = Expression.Property(niche, categoryProperty2); ConstantExpression value = Expression.Constant(query.StringValue); right = Expression.Equal(niche_Url_Id, value); } } // Product Rating else if (query.QueryType == QueryType.ProductRating) { PropertyInfo ratingProperty = typeof(Product).GetProperty("Rating"); MemberExpression rating = Expression.Property(product, ratingProperty); ConstantExpression value = Expression.Constant(query.DoubleValue); if (query.ComparisonOperator == ComparisonOperatorType.Equal) { right = Expression.Equal(rating, value); } if (query.ComparisonOperator == ComparisonOperatorType.NotEqual) { right = Expression.NotEqual(rating, value); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThan) { right = Expression.GreaterThan(rating, value); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThanOrEqual) { right = Expression.GreaterThanOrEqual(rating, value); } if (query.ComparisonOperator == ComparisonOperatorType.LessThan) { right = Expression.LessThan(rating, value); } if (query.ComparisonOperator == ComparisonOperatorType.LessThanOrEqual) { right = Expression.LessThanOrEqual(rating, value); } } // Product Price else if (query.QueryType == QueryType.ProductPrice) { PropertyInfo priceProperty1 = typeof(Product).GetProperty("MinPrice"); PropertyInfo priceProperty2 = typeof(Product).GetProperty("MaxPrice"); MemberExpression minPrice = Expression.Property(product, priceProperty1); MemberExpression maxPrice = Expression.Property(product, priceProperty2); ConstantExpression zero = Expression.Constant(0.0); ConstantExpression value = Expression.Constant(query.DoubleValue); if (query.ComparisonOperator == ComparisonOperatorType.Equal) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.Equal(minPrice, value)), Expression.Equal(maxPrice, value)); } if (query.ComparisonOperator == ComparisonOperatorType.NotEqual) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.NotEqual(minPrice, value)), Expression.NotEqual(maxPrice, value)); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThan) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.GreaterThan(minPrice, value)), Expression.GreaterThan(maxPrice, value)); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThanOrEqual) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.GreaterThanOrEqual(minPrice, value)), Expression.GreaterThanOrEqual(maxPrice, value)); } if (query.ComparisonOperator == ComparisonOperatorType.LessThan) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.LessThan(minPrice, value)), Expression.LessThan(maxPrice, value)); } if (query.ComparisonOperator == ComparisonOperatorType.LessThanOrEqual) { right = Expression.OrElse(Expression.AndAlso(Expression.Equal(maxPrice, zero), Expression.LessThanOrEqual(minPrice, value)), Expression.LessThanOrEqual(maxPrice, value)); } } // Product Subgroup, Product Keywords, or Featured Products else if (query.QueryType == QueryType.ProductSubgroup || query.QueryType == QueryType.ProductKeywords || query.QueryType == QueryType.FeaturedProducts) { PropertyInfo productProperty = typeof(Product).GetProperty("Id"); MemberExpression productId = Expression.Property(product, productProperty); ConstantExpression values = Expression.Constant(query.IntValues); MethodInfo method = query.IntValues.GetType().GetMethod("Contains"); MethodCallExpression call = Expression.Call(values, method, productId); right = Expression.Equal(call, Expression.Constant(true)); } // Product Creation Date else if (query.QueryType == QueryType.ProductCreationDate) { PropertyInfo dateProperty = typeof(Product).GetProperty("Date"); MemberExpression date = Expression.Property(product, dateProperty); ConstantExpression value = Expression.Constant(query.DateValue); if (query.ComparisonOperator == ComparisonOperatorType.Equal) { right = Expression.Equal(date, value); } if (query.ComparisonOperator == ComparisonOperatorType.NotEqual) { right = Expression.NotEqual(date, value); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThan) { right = Expression.GreaterThan(date, value); } if (query.ComparisonOperator == ComparisonOperatorType.GreaterThanOrEqual) { right = Expression.GreaterThanOrEqual(date, value); } if (query.ComparisonOperator == ComparisonOperatorType.LessThan) { right = Expression.LessThan(date, value); } if (query.ComparisonOperator == ComparisonOperatorType.LessThanOrEqual) { right = Expression.LessThanOrEqual(date, value); } } // Subquery else if (query.QueryType == QueryType.SubQuery) { right = GetQueries(query.SubQueries); } if (left.Count == 0) { left.Add(right); } if (left[^ 1] != right)
protected virtual Expression VisitConstant(ConstantExpression node) { return(null); }
protected override Expression VisitConstant(ConstantExpression node) { this.count = (int)node.Value; return(base.VisitConstant(node)); }
static void DisplayTree(int indent, string message, Expression expression) { string output = $"{string.Empty.PadLeft(indent, '>')}{message}" + $"!NodeType:{expression.NodeType};Expr:{expression}"; indent++; switch (expression.NodeType) { case ExpressionType.Add: break; case ExpressionType.AddAssign: break; case ExpressionType.AddAssignChecked: break; case ExpressionType.AddChecked: break; case ExpressionType.And: break; case ExpressionType.AndAlso: break; case ExpressionType.AndAssign: break; case ExpressionType.ArrayIndex: break; case ExpressionType.ArrayLength: break; case ExpressionType.Assign: break; case ExpressionType.Block: break; case ExpressionType.Call: break; case ExpressionType.Coalesce: break; case ExpressionType.Conditional: break; case ExpressionType.Constant: ConstantExpression constExpr = (ConstantExpression)expression; Console.WriteLine($"{output} Const Value{constExpr.Value}"); break; case ExpressionType.Convert: break; case ExpressionType.ConvertChecked: break; case ExpressionType.DebugInfo: break; case ExpressionType.Decrement: break; case ExpressionType.Default: break; case ExpressionType.Divide: break; case ExpressionType.DivideAssign: break; case ExpressionType.Dynamic: break; case ExpressionType.Equal: break; case ExpressionType.ExclusiveOr: break; case ExpressionType.ExclusiveOrAssign: break; case ExpressionType.Extension: break; case ExpressionType.Goto: break; case ExpressionType.GreaterThan: BinaryExpression binExpr = (BinaryExpression)expression; if (binExpr.Method != null) { Console.WriteLine($"{output} Method:{binExpr.Method.Name}"); } else { Console.WriteLine(output); } DisplayTree(indent, "Left", binExpr.Left); DisplayTree(indent, "Right", binExpr.Right); break; case ExpressionType.GreaterThanOrEqual: break; case ExpressionType.Increment: break; case ExpressionType.Index: break; case ExpressionType.Invoke: break; case ExpressionType.IsFalse: break; case ExpressionType.IsTrue: break; case ExpressionType.Label: break; case ExpressionType.Lambda: Console.WriteLine(output); LambdaExpression lambdaExpression = (LambdaExpression)expression; foreach (var parameter in lambdaExpression.Parameters) { DisplayTree(indent, "Parameter", parameter); } DisplayTree(indent, "Body", lambdaExpression.Body); break; case ExpressionType.LeftShift: break; case ExpressionType.LeftShiftAssign: break; case ExpressionType.LessThan: break; case ExpressionType.LessThanOrEqual: break; case ExpressionType.ListInit: break; case ExpressionType.Loop: break; case ExpressionType.MemberAccess: MemberExpression memberExpr = (MemberExpression)expression; Console.WriteLine($"{output}Member Name{memberExpr.Member.Name}Type{memberExpr.Expression}"); break; case ExpressionType.MemberInit: break; case ExpressionType.Modulo: break; case ExpressionType.ModuloAssign: break; case ExpressionType.Multiply: break; case ExpressionType.MultiplyAssign: break; case ExpressionType.MultiplyAssignChecked: break; case ExpressionType.MultiplyChecked: break; case ExpressionType.Negate: break; case ExpressionType.NegateChecked: break; case ExpressionType.New: break; case ExpressionType.NewArrayBounds: break; case ExpressionType.NewArrayInit: break; case ExpressionType.Not: break; case ExpressionType.NotEqual: break; case ExpressionType.OnesComplement: break; case ExpressionType.Or: break; case ExpressionType.OrAssign: break; case ExpressionType.OrElse: break; case ExpressionType.Parameter: ParameterExpression paramExpr = (ParameterExpression)expression; Console.WriteLine($"{output} Param Type:{paramExpr.Type.Name}"); break; case ExpressionType.PostDecrementAssign: break; case ExpressionType.PostIncrementAssign: break; case ExpressionType.Power: break; case ExpressionType.PowerAssign: break; case ExpressionType.PreDecrementAssign: break; case ExpressionType.PreIncrementAssign: break; case ExpressionType.Quote: break; case ExpressionType.RightShift: break; case ExpressionType.RightShiftAssign: break; case ExpressionType.RuntimeVariables: break; case ExpressionType.Subtract: break; case ExpressionType.SubtractAssign: break; case ExpressionType.SubtractAssignChecked: break; case ExpressionType.SubtractChecked: break; case ExpressionType.Switch: break; case ExpressionType.Throw: break; case ExpressionType.Try: break; case ExpressionType.TypeAs: break; case ExpressionType.TypeEqual: break; case ExpressionType.TypeIs: break; case ExpressionType.UnaryPlus: break; case ExpressionType.Unbox: break; default: Console.WriteLine(); Console.WriteLine($"{expression.NodeType}{expression.Type.Name}"); break; } }
/// <summary> /// 验证重复数据 /// </summary> protected void ValidateDuplicateData() { //获取设定的重复字段信息 var checkCondition = SetDuplicatedCheck(); if (checkCondition != null && checkCondition.Groups.Count > 0) { //生成基础Query var baseExp = DC.Set <TModel>().AsQueryable(); var modelType = typeof(TModel); ParameterExpression para = Expression.Parameter(modelType, "tm"); //循环所有重复字段组 foreach (var group in checkCondition.Groups) { List <Expression> conditions = new List <Expression>(); //生成一个表达式,类似于 x=>x.Id != id,这是为了当修改数据时验证重复性的时候,排除当前正在修改的数据 MemberExpression idLeft = Expression.Property(para, "Id"); ConstantExpression idRight = Expression.Constant(Entity.ID); BinaryExpression idNotEqual = Expression.NotEqual(idLeft, idRight); conditions.Add(idNotEqual); List <PropertyInfo> props = new List <PropertyInfo>(); //在每个组中循环所有字段 foreach (var field in group.Fields) { Expression exp = field.GetExpression(Entity, para); if (exp != null) { conditions.Add(exp); } //将字段名保存,为后面生成错误信息作准备 props.AddRange(field.GetProperties()); } int count = 0; if (conditions.Count > 1) { //循环添加条件并生成Where语句 Expression conExp = conditions[0]; for (int i = 1; i < conditions.Count; i++) { conExp = Expression.And(conExp, conditions[i]); } MethodCallExpression whereCallExpression = Expression.Call( typeof(Queryable), "Where", new Type[] { modelType }, baseExp.Expression, Expression.Lambda <Func <TModel, bool> >(conExp, new ParameterExpression[] { para })); var result = baseExp.Provider.CreateQuery(whereCallExpression); foreach (var res in result) { count++; } } if (count > 0) { //循环拼接所有字段名 string AllName = ""; foreach (var prop in props) { string name = PropertyHelper.GetPropertyDisplayName(prop); AllName += name + ","; } if (AllName.EndsWith(",")) { AllName = AllName.Remove(AllName.Length - 1); } //如果只有一个字段重复,则拼接形成 xxx字段重复 这种提示 if (props.Count == 1) { MSD.AddModelError(GetValidationFieldName(props[0])[0], AllName + "字段重复"); } //如果多个字段重复,则拼接形成 xx,yy,zz组合字段重复 这种提示 else if (props.Count > 1) { MSD.AddModelError(GetValidationFieldName(props.First())[0], AllName + "字段组合重复"); } } } } }
protected override object VisitConstant(ConstantExpression exp) { return(exp.Value); }
protected virtual Expression VisitConstant(ConstantExpression c) { return(c); }
static object GetValue(ConstantExpression methodCall) { return(methodCall.Value); }
/// <summary> /// CompareConstant /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> protected virtual int CompareConstant(ConstantExpression x, ConstantExpression y) { return(Comparer.Default.Compare(x.Value, y.Value)); }
protected override Expression VisitConstant(ConstantExpression node) { return(base.VisitConstant(node)); }
protected virtual Expression VisitConstantExpression(ConstantExpression expression) { ArgumentUtility.CheckNotNull("expression", expression); return(expression); }
/// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public abstract bool TryPrintConstant( [NotNull] ConstantExpression constantExpression, [NotNull] IndentedStringBuilder stringBuilder, bool removeFormatting);
private static string Resolve(Expression expression) { if (expression is LambdaExpression) { LambdaExpression lambda = expression as LambdaExpression; expression = lambda.Body; return(Resolve(expression)); } if (expression is BinaryExpression) { BinaryExpression binary = expression as BinaryExpression; if (binary.Left is MemberExpression && binary.Right is ConstantExpression)//解析x=>x.Name=="123" x.Age==123这类 { return(ResolveFunc(binary.Left, binary.Right, binary.NodeType)); } if (binary.Left is MethodCallExpression && binary.Right is ConstantExpression)//解析x=>x.Name.Contains("xxx")==false这类的 { object value = (binary.Right as ConstantExpression).Value; return(ResolveLinqToObject(binary.Left, value, binary.NodeType)); } if ((binary.Left is MemberExpression && binary.Right is MemberExpression) || (binary.Left is MemberExpression && binary.Right is UnaryExpression)) //解析x=>x.Date==DateTime.Now这种 { LambdaExpression lambda = Expression.Lambda(binary.Right); Delegate fn = lambda.Compile(); ConstantExpression value = Expression.Constant(fn.DynamicInvoke(null), binary.Right.Type); return(ResolveFunc(binary.Left, value, binary.NodeType)); } } if (expression is UnaryExpression) { UnaryExpression unary = expression as UnaryExpression; if (unary.Operand is MethodCallExpression)//解析!x=>x.Name.Contains("xxx")或!array.Contains(x.Name)这类 { return(ResolveLinqToObject(unary.Operand, false)); } if (unary.Operand is MemberExpression && unary.NodeType == ExpressionType.Not)//解析x=>!x.isDeletion这样的 { ConstantExpression constant = Expression.Constant(false); return(ResolveFunc(unary.Operand, constant, ExpressionType.Equal)); } } if (expression is MemberExpression && expression.NodeType == ExpressionType.MemberAccess)//解析x=>x.isDeletion这样的 { MemberExpression member = expression as MemberExpression; ConstantExpression constant = Expression.Constant(true); return(ResolveFunc(member, constant, ExpressionType.Equal)); } if (expression is MethodCallExpression)//x=>x.Name.Contains("xxx")或array.Contains(x.Name)这类 { MethodCallExpression methodcall = expression as MethodCallExpression; return(ResolveLinqToObject(methodcall, true)); } var body = expression as BinaryExpression; //已经修改过代码body应该不会是null值了 if (body == null) { return(string.Empty); } var Operator = GetOperator(body.NodeType); var Left = Resolve(body.Left); var Right = Resolve(body.Right); string Result = string.Format("({0} {1} {2})", Left, Operator, Right); return(Result); }
//表达式路由计算 public static string ExpressionRouter(Expression exp) { if (exp is MemberExpression) { MemberExpression me = ((MemberExpression)exp); return(me.Member.Name); } else if (exp is NewArrayExpression) { NewArrayExpression ae = ((NewArrayExpression)exp); StringBuilder tmpstr = new StringBuilder(); foreach (Expression ex in ae.Expressions) { tmpstr.Append(ExpressionRouter(ex)); tmpstr.Append(","); } return(tmpstr.ToString(0, tmpstr.Length - 1)); } else if (exp is MethodCallExpression) { MethodCallExpression mce = (MethodCallExpression)exp; if (mce.Method.Name == "Like") { return(string.Format("({0} LIKE {1})", ExpressionRouter(mce.Arguments[0]), ExpressionRouter(mce.Arguments[1]))); } else if (mce.Method.Name == "NotLike") { return(string.Format("({0} Not LIKE {1})", ExpressionRouter(mce.Arguments[0]), ExpressionRouter(mce.Arguments[1]))); } else if (mce.Method.Name == "In") { return(string.Format("{0} IN ({1})", ExpressionRouter(mce.Arguments[0]), ExpressionRouter(mce.Arguments[1]))); } else if (mce.Method.Name == "NotIn") { return(string.Format("{0} NOT IN ({1})", ExpressionRouter(mce.Arguments[0]), ExpressionRouter(mce.Arguments[1]))); } } else if (exp is ConstantExpression) { ConstantExpression ce = ((ConstantExpression)exp); if (ce.Value == null) { return("null"); } else if (ce.Value is ValueType) { return(ce.Value.ToString()); } else if (ce.Value is string || ce.Value is DateTime || ce.Value is char) { return(string.Format("'{0}'", ce.Value.ToString())); } } else if (exp is UnaryExpression) { UnaryExpression ue = ((UnaryExpression)exp); return(ExpressionRouter(ue.Operand)); } return(null); }
protected virtual void VisitConstant(ConstantExpression node) { ConstantReference(node?.Value); }
/// <summary> /// Generates the node structure required to generate a default /// initialization. /// </summary> /// <param name = "p"> /// Tools.Parser instance to use when instantiating nodes. /// </param> /// <param name = "constantType">String describing the datatype.</param> /// <returns> /// A SYMBOL node conaining the appropriate structure for intializing a /// constantType. /// </returns> private SYMBOL GetZeroConstant(Parser p, string constantType) { switch (constantType) { case "integer": return new Constant(p, constantType, "0"); case "float": return new Constant(p, constantType, "0.0"); case "string": case "key": return new Constant(p, constantType, ""); case "list": ArgumentList al = new ArgumentList(p); return new ListConstant(p, al); case "vector": Constant vca = new Constant(p, "float", "0.0"); Constant vcb = new Constant(p, "float", "0.0"); Constant vcc = new Constant(p, "float", "0.0"); ConstantExpression vcea = new ConstantExpression(p, vca); ConstantExpression vceb = new ConstantExpression(p, vcb); ConstantExpression vcec = new ConstantExpression(p, vcc); return new VectorConstant(p, vcea, vceb, vcec); case "rotation": Constant rca = new Constant(p, "float", "0.0"); Constant rcb = new Constant(p, "float", "0.0"); Constant rcc = new Constant(p, "float", "0.0"); Constant rcd = new Constant(p, "float", "0.0"); ConstantExpression rcea = new ConstantExpression(p, rca); ConstantExpression rceb = new ConstantExpression(p, rcb); ConstantExpression rcec = new ConstantExpression(p, rcc); ConstantExpression rced = new ConstantExpression(p, rcd); return new RotationConstant(p, rcea, rceb, rcec, rced); default: return null; // this will probably break stuff } }
/// <summary> /// Creates a <see cref="ConstantExpression"/> that has the <see cref="P:ConstantExpression.Value"/> property set to the specified value. . /// </summary> /// <param name="value">An <see cref="System.Object"/> to set the <see cref="P:ConstantExpression.Value"/> property equal to.</param> /// <returns> /// A <see cref="ConstantExpression"/> that has the <see cref="P:Expression.NodeType"/> property equal to /// <see cref="F:ExpressionType.Constant"/> and the <see cref="P:Expression.Value"/> property set to the specified value. /// </returns> public static ConstantExpression Constant(object value) { return(ConstantExpression.Make(value, value == null ? typeof(object) : value.GetType())); }
static object GetRuntimeConstant(ConstantExpression ce) { if (ce.Value is Microsoft.Scripting.Generation.CompilerConstant) { var cc = (Microsoft.Scripting.Generation.CompilerConstant)ce.Value; return cc.Create(); } return ce.Value; }
public MyConstantExpression(ConstantExpression expression) { _expression = expression; }
// ConstantExpression protected internal virtual bool Walk(ConstantExpression node) { return true; }
protected override Expression VisitConstant(ConstantExpression constantExpression) => constantExpression.Type.GetTypeInfo().IsGenericType && constantExpression.Type.GetGenericTypeDefinition() == typeof(EntityQueryable <>) ? VisitEntityQueryable(((IQueryable)constantExpression.Value).ElementType) : constantExpression;
public void CanFindItems(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); IList<Expression> expressions = block.Expressions; for (int i = 0; i != values.Length; ++i) Assert.Equal(i, expressions.IndexOf(values[i])); }
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override Expression VisitConstant(ConstantExpression constantExpression) { Check.NotNull(constantExpression, nameof(constantExpression)); return(new SqlConstantExpression(constantExpression, null)); }
// ConstantExpression public override bool Walk(ConstantExpression node) { return false; }
/// <summary> /// Visits a ConstantExpression. /// </summary> /// <param name="node">The ConstantExpression.</param> /// <returns>The result of visiting the Expression.</returns> protected virtual T VisitConstant(ConstantExpression node) { return(default(T)); }
// ConstantExpression public virtual bool Walk(ConstantExpression node) { return true; }
protected override Expression VisitConstant(ConstantExpression node) { _rootNode = new TreeNode(node.ToString()); return(node); }
private void EmitConstantExpression(Expression expr) { ConstantExpression node = (ConstantExpression)expr; EmitConstant(node.Value, node.Type); }
public ConstantExpressionProxy(ConstantExpression node) { _node = node; }
public override bool Walk(ConstantExpression node) { AddTagIfNecessary(_ast.GetLineEndFromPosition(node.StartIndex), node.EndIndex); return(base.Walk(node)); }
public override bool Walk(ConstantExpression node) { node.Parent = _currentScope; return base.Walk(node); }
private static bool CompareConstant(ConstantExpression a, ConstantExpression b) => Equals(a.Value, b.Value);
protected override Expression VisitConstant(ConstantExpression node) { return Expression.Constant(node.Value, node.Type); // clones }
protected abstract T GetResultFromConstant(ConstantExpression node);
protected internal virtual void PostWalk(ConstantExpression node) { }
protected sealed override Expression VisitConstant(ConstantExpression node) { Result = resultVisitor.GetResultFromConstant(node); return(node); }
public void ExpressionsEnumerable(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(SingleParameter, values); Assert.True(values.SequenceEqual(block.Expressions)); int index = 0; foreach (Expression exp in ((IEnumerable)block.Expressions)) Assert.Same(exp, values[index++]); }
protected override Expression VisitConstant(ConstantExpression node) { _filter.Append(ConvertSqlLiteral(node.Value, node.Type)); return(node); }
public override void PostWalk(ConstantExpression node) { }
internal virtual Expression VisitConstant(ConstantExpression c) { return(c); }
public virtual void PostWalk(ConstantExpression node) { }
protected override Expression VisitConstant(ConstantExpression node) { return(node.Value == _originalQueryable ? _replacementQueryable : node); }