상속: Expression
 private static void PrintNode(BinaryExpression expression,
   int indent)
 {
     PrintNode(expression.Left, indent + 1);
     PrintSingle(expression, indent);
     PrintNode(expression.Right, indent + 1);
 }
        static NSLayoutConstraint CompileConstraint(BinaryExpression expr, UIView constrainedView)
        {
            var rel = NSLayoutRelation.Equal;
            switch (expr.NodeType)
            {
                case ExpressionType.Equal:
                    rel = NSLayoutRelation.Equal;
                    break;
                case ExpressionType.LessThanOrEqual:
                    rel = NSLayoutRelation.LessThanOrEqual;
                    break;
                case ExpressionType.GreaterThanOrEqual:
                    rel = NSLayoutRelation.GreaterThanOrEqual;
                    break;
                default:
                    throw new NotSupportedException("Not a valid relationship for a constrain.");
            }

            var left = GetViewAndAttribute(expr.Left);
            if (left.Item1 != constrainedView)
            {
                left.Item1.TranslatesAutoresizingMaskIntoConstraints = false;
            }

            var right = GetRight(expr.Right);

            return NSLayoutConstraint.Create(
                left.Item1, left.Item2,
                rel,
                right.Item1, right.Item2,
                right.Item3, right.Item4);
        }
예제 #3
0
        public ContainmentWhereFragment(ISerializer serializer, BinaryExpression binary)
        {
            _serializer = serializer;

            var visitor = new FindMembers();
            visitor.Visit(binary.Left);

            var members = visitor.Members;

            if (members.Count > 1)
            {
                var dict = new Dictionary<string, object>();
                var member = members.Last();
                var value = MartenExpressionParser.Value(binary.Right);
                dict.Add(member.Name, value);

                members.Reverse().Skip(1).Each(m =>
                {
                    dict = new Dictionary<string, object> { { m.Name, dict}};
                });

                _dictionary = dict;
            }
            else
            {
                _dictionary = new Dictionary<string, object>();

                var member = members.Single();
                var value = MartenExpressionParser.Value(binary.Right);
                _dictionary.Add(member.Name, value);

            }
        }
예제 #4
0
 protected override Expression VisitBinary(BinaryExpression node)
 {
     switch(node.NodeType) {
     case ExpressionType.Equal:
     case ExpressionType.NotEqual:
       if(_model.IsEntity(node.Left.Type) || _model.IsEntity(node.Right.Type)) {
     //visit children and replace with EntitiesEqual
     var newLeft = Visit(node.Left);
     var newRight = Visit(node.Right);
     var method = node.NodeType == ExpressionType.Equal ? EntityCacheHelper.EntitiesEqualMethod : EntityCacheHelper.EntitiesNotEqualMethod;
     return Expression.Call(null, method, newLeft, newRight);
       }//if
       // compare both args, to cover expr like 'p.Name == null'
       if (node.Left.Type == typeof(string) && node.Right.Type == typeof(string) && _caseMode == StringCaseMode.CaseInsensitive) {
     var baseLeft = base.Visit(node.Left);
     var baseRight = base.Visit(node.Right);
     Expression result = Expression.Call(EntityCacheHelper.StringStaticEquals3Method,
                                          baseLeft, baseRight, EntityCacheHelper.ConstInvariantCultureIgnoreCase);
     if (node.NodeType == ExpressionType.NotEqual)
       result = Expression.Not(result);
     return result;
       }
       break;
       }//switch
       return base.VisitBinary(node);
 }
예제 #5
0
        protected override Expression VisitBinary(BinaryExpression binaryExpression)
        {
            if (binaryExpression.NodeType == ExpressionType.Or
                || binaryExpression.NodeType == ExpressionType.And
                || binaryExpression.NodeType == ExpressionType.OrElse
                || binaryExpression.NodeType == ExpressionType.AndAlso
                && binaryExpression.Type.GetUnwrappedNullableType() == typeof(bool))
            {
                var left = this.Visit(binaryExpression.Left);
                var right = this.Visit(binaryExpression.Right);

                if (left.Type.GetUnwrappedNullableType() == typeof(bool) && (left is BitBooleanExpression))
                {
                    left = Expression.Equal(left, Expression.Constant(true));
                }

                if (right.Type.GetUnwrappedNullableType() == typeof(bool) && (right is BitBooleanExpression))
                {
                    right = Expression.Equal(right, Expression.Constant(false));
                }

                if (left != binaryExpression.Left || right != binaryExpression.Right)
                {
                    return Expression.MakeBinary(binaryExpression.NodeType, left, right);
                }
            }

            return base.VisitBinary(binaryExpression);
        }
 protected override Expression VisitBinary(BinaryExpression binaryExpression)
 {
     using (this.AcquireDisableCompareContext())
     {
         return base.VisitBinary(binaryExpression);
     }
 }
예제 #7
0
		protected override Expression VisitBinary(BinaryExpression binaryExpr)
		{
			ResourceProperty resourceProperty = null;
			object obj = null;
			if (!ExpressionHelper.ContainsComparisonOperator(binaryExpr))
			{
				if (!ExpressionHelper.ContainsLogicalOperator(binaryExpr))
				{
					this.IsCompleteExpressionParsed = false;
				}
			}
			else
			{
				if (!ExpressionHelper.GetPropertyNameAndValue(binaryExpr, out resourceProperty, out obj))
				{
					TraceHelper.Current.DebugMessage("Expression is too complex to execute");
					this.IsCompleteExpressionParsed = false;
				}
				else
				{
					this.FilterProperties.Add(new KeyValuePair<ResourceProperty, object>(resourceProperty, obj));
				}
			}
			return base.VisitBinary(binaryExpr);
		}
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            var allowedProperties = new[] { "Project", "Definition", "Number", "Reason", "Quality", "Status", "RequestedBy", "RequestedFor", "StartTime", "FinishTime", "BuildFinished" };

            if (node.NodeType == ExpressionType.OrElse)
            {
                throw new NotSupportedException("Logical OR operators are not supported for Build Custom filters");
            }

            if (node.Left is MemberExpression && node.Right is ConstantExpression)
            {
                var fieldName = (node.Left as MemberExpression).Member.Name;
                var value = (node.Right as ConstantExpression).Value;

                if (!allowedProperties.ToList().Contains(fieldName))
                {
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "You can only filter by the following properties: {0}. (e.g. /Builds/$filter=Number gt 100 and  Quality eq 'Healthy') ", string.Join(", ", allowedProperties)));
                }

                this.AddFilterNode(fieldName, value, FilterNode.ParseFilterExpressionType(node.NodeType), FilterNodeRelationship.And);
            }
            else if (node.Left.NodeType == ExpressionType.Conditional)
            {
                throw new NotSupportedException("Only equality and inequality operators between fields and constant expressions are allowed with Build Custom filters");
            }

            return base.VisitBinary(node);
        }
        internal static string GetValueFromEqualsExpression(BinaryExpression be, Type memberDeclaringType, string memberName)
        {
            if (be.NodeType != ExpressionType.Equal)
                throw new Exception("There is a bug in this program.");

            if (be.Left.NodeType == ExpressionType.MemberAccess)
            {
                MemberExpression me = (MemberExpression)be.Left;

                if (IsSameTypeOrSubType(me.Member.DeclaringType, memberDeclaringType) && me.Member.Name == memberName)
                {
                    return GetValueFromExpression(be.Right);
                }
            }
            else if (be.Right.NodeType == ExpressionType.MemberAccess)
            {
                MemberExpression me = (MemberExpression)be.Right;

                if (IsSameTypeOrSubType(me.Member.DeclaringType, memberDeclaringType) && me.Member.Name == memberName)
                {
                    return GetValueFromExpression(be.Left);
                }
            }

            // We should have returned by now.
            throw new Exception("There is a bug in this program.");
        }
예제 #10
0
        public static void CreateDictionaryForSearch(BinaryExpression binary, IDictionary<string, object> dict)
        {
            var expressionValue = binary.Right.Value();
            var memberExpression = binary.Left;

            CreateDictionaryForSearch(dict, memberExpression, expressionValue);
        }
        protected override Expression VisitBinary(BinaryExpression node)
        {
            // a ?? b == null <-> a == null && b == null
            if (node.NodeType == ExpressionType.Coalesce)
            {
                var current = ResultExpression;
                ResultExpression = null;
                Visit(node.Left);
                var left = ResultExpression;

                ResultExpression = null;
                Visit(node.Right);
                var right = ResultExpression;

                var coalesce = CombineExpressions(left, right, ExpressionType.AndAlso);

                ResultExpression = current;
                AddToResult(coalesce);
            }

            // a && b == null <-> a == null && b != false || a != false && b == null
            // this transformation would produce a query that is too complex
            // so we just wrap the whole expression into IsNullExpression instead.
            if ((node.NodeType == ExpressionType.AndAlso)
                || (node.NodeType == ExpressionType.OrElse))
            {
                AddToResult(new IsNullExpression(node));
            }

            return node;
        }
예제 #12
0
 protected override Expression VisitBinary(BinaryExpression node)
 {
     // rewrite not equal
     if (node.NodeType == ExpressionType.NotEqual)
     {
         return
             Visit(Expression.MakeUnary(ExpressionType.Not,
                 Expression.MakeBinary(ExpressionType.Equal, node.Left, node.Right), node.Type));
     }
     // handle
     _query.Append("(");
     Visit(node.Left);
     switch (node.NodeType)
     {
         case ExpressionType.AndAlso:
             _query.Append(" AND ");
             break;
         case ExpressionType.OrElse:
             _query.Append(" OR ");
             break;
         case ExpressionType.Equal:
             _query.Append(":");
             break;
     }
     Visit(node.Right);
     _query.Append(")");
     // done
     return node;
 }
예제 #13
0
 protected override Expression VisitBinary(BinaryExpression node)
 {
     var relation = string.Empty;
     switch (node.NodeType)
     {
         case ExpressionType.Equal:
             relation = " = ";
             break;
         case ExpressionType.NotEqual:
             relation = " <> ";
             break;
         case ExpressionType.GreaterThan:
             relation = " > ";
             break;
         case ExpressionType.GreaterThanOrEqual:
             relation = " >= ";
             break;
         case ExpressionType.LessThan:
             relation = " < ";
             break;
         case ExpressionType.LessThanOrEqual:
             relation = " <= ";
             break;
         case ExpressionType.Add:
             relation = " + ";
             break;
         case ExpressionType.Subtract:
             relation = " - ";
             break;
         default:
             break;
     }
     this.Condition = GetRelationCondition(relation, node);
     return node;
 }
        protected override Expression VisitBinary(BinaryExpression node)
        {
            // Go and visit the left hand side of this expression
            this.Visit(node.Left);

            // Add the operator in the middle
            switch (node.NodeType)
            {
                case ExpressionType.Equal:
                    this.sql.Append("=");
                break;

                case ExpressionType.And:
                case ExpressionType.AndAlso:
                case ExpressionType.Or:
                case ExpressionType.OrElse:
                    this.sql.Append(",");
                break;

                default:
                    throw new Exception
                    (
                        "Operator Not Known => " + node.NodeType
                    );
            }

            // Operator needs a space after it.
            this.sql.Append(" ");

            // Now visit the right hand side of this expression.
            this.Visit(node.Right);

            return node;
        }
		protected override Expression VisitBinary(BinaryExpression binaryExpression)
		{
			var nodeType = binaryExpression.NodeType;

			if (nodeType == ExpressionType.Equal || nodeType == ExpressionType.NotEqual)
			{
				var left = this.Visit(binaryExpression.Left).StripAndGetConstant();
				var right = this.Visit(binaryExpression.Right).StripAndGetConstant();

				if (left != null && right != null)
				{
					if (left.Value == null && right.Value == null)
					{
						return Expression.Constant(true);
					}

					if (left.Value == null || right.Value == null)
					{
						return Expression.Constant(false);
					}
				}

				if (left != null && left.Value == null)
				{
					return new SqlFunctionCallExpression(binaryExpression.Type, nodeType == ExpressionType.Equal ? SqlFunction.IsNull : SqlFunction.IsNotNull, binaryExpression.Right);
				}
				else if (right != null && right.Value == null)
				{
					return new SqlFunctionCallExpression(binaryExpression.Type, nodeType == ExpressionType.Equal ? SqlFunction.IsNull : SqlFunction.IsNotNull, binaryExpression.Left);
				}
			}

			return base.VisitBinary(binaryExpression);
		}
예제 #16
0
        protected override Expression VisitBinary(BinaryExpression b)
        {
            b = base.VisitBinary(b) as BinaryExpression;

            switch (b.NodeType)
            {
                case ExpressionType.Add:
                case ExpressionType.AddChecked:
                    if (b.Left.Type.Equals(typeof(String)))
                        return Expression.Call(MethodRepository.Concat, Expression.NewArrayInit(Types.String, b.Left, Expressor.ToString(b.Right)));
                    if (b.Right.Type.Equals(typeof(String)))
                        return Expression.Call(MethodRepository.Concat, Expression.NewArrayInit(Types.String, Expressor.ToString(b.Left), b.Right));
                    return b;
                case ExpressionType.ArrayIndex:
                    if (b.Type == Types.Byte)
                    {

                    }
                    return b;
                case ExpressionType.Equal:
                case ExpressionType.NotEqual:
                default:
                    return b;
            }
        }
예제 #17
0
        protected override Expression VisitBinary(BinaryExpression node)
        {
            base.Visit(node.Right);

            switch (node.NodeType)
            {
                case ExpressionType.Equal:
                    _expressionFragments.Push(" == ");
                    break;
                case ExpressionType.NotEqual:
                    _expressionFragments.Push(" != ");
                    break;
                case ExpressionType.LessThan:
                    _expressionFragments.Push(" < ");
                    break;
                case ExpressionType.LessThanOrEqual:
                    _expressionFragments.Push(" <= ");
                    break;
                case ExpressionType.GreaterThan:
                    _expressionFragments.Push(" > ");
                    break;
                case ExpressionType.GreaterThanOrEqual:
                    _expressionFragments.Push(" >= ");
                    break;
                default:
                    _isValidXeroObjectPath = false;
                    return null;
            }

            base.Visit(node.Left);

            return node;
        }
예제 #18
0
        protected override Expression VisitBinary(BinaryExpression binaryExpression)
        {
            var left = this.Visit(binaryExpression.Left);
            var right = this.Visit(binaryExpression.Right);

            if (left.Type.GetUnwrappedNullableType().IsEnum)
            {
                if (!right.Type.GetUnwrappedNullableType().IsEnum)
                {
                    right = Expression.Convert(Expression.Call(null, MethodInfoFastRef.EnumToObjectMethod, Expression.Constant(left.Type.GetUnwrappedNullableType()), Expression.Convert(right, typeof(int))), left.Type);
                }
            }
            else if (right.Type.GetUnwrappedNullableType().IsEnum)
            {
                if (!left.Type.GetUnwrappedNullableType().IsEnum)
                {
                    left = Expression.Convert(Expression.Call(null, MethodInfoFastRef.EnumToObjectMethod, Expression.Constant(right.Type.GetUnwrappedNullableType()), Expression.Convert(left, typeof(int))), right.Type);
                }
            }

            if (left != binaryExpression.Left || right != binaryExpression.Right)
            {
                return Expression.MakeBinary(binaryExpression.NodeType, left, right);
            }

            return binaryExpression;
        }
        protected override Expression VisitBinary(BinaryExpression b)
        {
            this.Visit(b.Left);
            switch (b.NodeType) {
                case ExpressionType.And | ExpressionType.AndAlso:
                    sb.Append(" and ");
                    break;
                case ExpressionType.Or:
                    sb.Append(" OR");
                    break;
                case ExpressionType.Equal:
                    sb.Append(" = ");
                    break;
                case ExpressionType.NotEqual:
                    sb.Append(" != ");
                    break;
                case ExpressionType.LessThan:
                    sb.Append(" < ");
                    break;
                case ExpressionType.LessThanOrEqual:
                    sb.Append(" <= ");
                    break;
                case ExpressionType.GreaterThan:
                    sb.Append(" > ");
                    break;
                case ExpressionType.GreaterThanOrEqual:
                    sb.Append(" >= ");
                    break;
                default:
                    throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported by SimpleDB.", b.NodeType));
            }

            this.Visit(b.Right);
            return b;
        }
예제 #20
0
            protected override Expression VisitBinary(BinaryExpression binary)
            {
                if (_operators.ContainsKey(binary.NodeType))
                {
                    var fragment = _parent.buildSimpleWhereClause(_mapping, binary);
                    _register.Peek()(fragment);

                    return null;
                }

                if ((binary.NodeType == ExpressionType.AndAlso) || (binary.NodeType == ExpressionType.OrElse))
                {
                    var separator = binary.NodeType == ExpressionType.AndAlso
                        ? "and"
                        : "or";

                    var compound = new CompoundWhereFragment(separator);
                    _register.Peek()(compound);
                    _register.Push(child => compound.Add(child));

                    Visit(binary.Left);
                    Visit(binary.Right);

                    _register.Pop();

                    return null;
                }


                throw new NotSupportedException($"Marten does not support the BinaryExpression {binary} (yet).");
            }
예제 #21
0
 protected override Expression VisitBinary(BinaryExpression node)
 {
     if (node.NodeType != ExpressionType.ArrayIndex)
         return base.VisitBinary(node);
     // rewrite...
     return Visit(node.Left).Array(Visit(node.Right));
 }
        static Expression SimpleProduct(Expression left, Expression right, BinaryExpression product)
        {
            // ensure "left" is no quotient
            if(left.NodeType == ExpressionType.Divide)
            {
                BinaryExpression leftQuotient = (BinaryExpression)left;
                Expression nominator = SimpleProduct(right, leftQuotient.Left, null);
                return SimpleQuotient(nominator, leftQuotient.Right, null);
            }

            // ensure "right" is no quotient
            if(right.NodeType == ExpressionType.Divide)
            {
                BinaryExpression rightQuotient = (BinaryExpression)right;
                Expression nominator = SimpleProduct(left, rightQuotient.Left, null);
                return SimpleQuotient(nominator, rightQuotient.Right, null);
            }

            // ensure "right" is no product
            while(right.NodeType == ExpressionType.Multiply)
            {
                BinaryExpression rightProduct = (BinaryExpression)right;
                left = Expression.Multiply(left, rightProduct.Right);
                right = rightProduct.Left;
            }

            if((product == null) || (left != product.Left) || (right != product.Right))
            {
                return Expression.Multiply(left, right);
            }

            return product;
        }
예제 #23
0
        protected List<Microsoft.Z3.BoolExpr> VisitBinary(BinaryExpression b)
        {
            // Use recursion to generate Z3 constraints for each operand of the binary expression
            // left side -> create a Z3 expression representing the left side
            Expression left = Visit(b.Left);

            // right side -> creat a Z3 expression representing the right side
            Expression right = Visit(b.Right);

            // Put those into a Z3 format
            ExpressionType op = b.NodeType;

            using (Context ctx = new Context())
            {
                if (op == ExpressionType.LessThan)
                {
                    // ctx.MkLt(left, right);
                }

            }

            Console.WriteLine(b.ToString());

            // TODO - return a Z3 expression
            return null;
        }
예제 #24
0
        /// <summary>
        ///     将二元符号转换成T-SQL可识别的操作符
        /// </summary>
        protected override Expression VisitBinary(BinaryExpression b)
        {
            if (b == null) { return null; }

            var isReverse = false;
            var left = b.Left;
            var right = b.Right;

            // 先解析字段
            if (b.Left.NodeType != ExpressionType.MemberAccess && (b.Left.NodeType == ExpressionType.MemberAccess || b.Right.NodeType == ExpressionType.MemberAccess)) { left = b.Right; right = b.Left; isReverse = true; }
            left = base.Visit(left);
            right = base.Visit(right);
            var conversion = base.Visit(b.Conversion);

            var contidion = isReverse ? (left != b.Right || right != b.Left) : (left != b.Left || right != b.Right);
            // 说明进过了换算
            if (contidion || conversion != b.Conversion)
            {
                if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) { return Expression.Coalesce(left, right, conversion as LambdaExpression); }
                else
                {

                    // 两边类型不同时,需要进行转换
                    if (left.Type != right.Type) { right = Expression.Convert(right, left.Type); }
                    b = Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
                }
            }

            // 清除状态(与或状态,不清除)
            if (b.NodeType != ExpressionType.And && b.NodeType != ExpressionType.Or) { CurrentFieldName = null; CurrentDbParameter = null; }
            return b;
        }
예제 #25
0
 protected override Expression VisitBinary(BinaryExpression node)
 {
     Visit(node.Left);
     ColumnName += node.NodeType;
     Visit(node.Right);
     return node;
 }
        /// <summary>
        /// Validates whether the binary expression is valid AND / OR expression.
        /// </summary>
        /// <param name="binaryExpression">Binary conjuctive expression.</param>
        public static void ValidateConjunctiveExpression(BinaryExpression binaryExpression)
        {
            Utils.ThrowIfNull(binaryExpression, "binaryExpression");

            ExpressionHelper.ValidateConjuctiveNode(binaryExpression.Left);
            ExpressionHelper.ValidateConjuctiveNode(binaryExpression.Right);
        }
예제 #27
0
        protected override Expression VisitBinary(BinaryExpression node)
        {
            if (node.NodeType == ExpressionType.Equal &&
                node.Left.ToString() == "element.Id")
            {
                try
                {
                    var stringEqualsMethod = typeof(string).GetMethod(
                        "Equals",
                        new[] { typeof(string), typeof(string), typeof(StringComparison) });
                    var newExpression = Expression.Call(
                        stringEqualsMethod,
                        node.Left,
                        node.Right,
                        Expression.Constant(StringComparison.OrdinalIgnoreCase));
                    return newExpression;
                }
                catch
                {
                    return base.VisitBinary(node);
                }
            }

            return base.VisitBinary(node);
        }
        protected override Expression VisitBinary(BinaryExpression node)
        {
            string operatorName;
            if (node.Method == null)
            {
                operatorName = string.Format(" {0} ", node.NodeType.GetName());
            }
            else
            {
                // VisitBinary should be called only for operators but its possible
                // that we don't know this special C# operators name

                var name = TypeNameConverter.GetCSharpOperatorName(node.Method);
                if (name != null)
                    operatorName = string.Format(" {0} ", name);
                else
                    operatorName = node.Method.Name;
            }
            // BinaryExpression consists of 3 parts: left operator right
            _rep = string.Format("{0}{1}{2}",
                Print(node.Left),
                operatorName,
                Print(node.Right));

            if (!_isHighLevel)
                _rep = string.Format("({0})", _rep);

            return node;
        }
        private static bool CheckShortCircuitOr(BinaryExpression expression, StringBuilder queryBuilder, Action<Expression> visitExpression)
        {
            if (expression.NodeType == ExpressionType.Or || expression.NodeType == ExpressionType.OrElse)
            {
                var ceLeft = expression.Left as ConstantExpression;
                var ceRight = expression.Right as ConstantExpression;

                if (ceLeft != null && (ceLeft.Type == typeof(bool) || ceLeft.Type == typeof(bool?)))
                {
                    if (true.Equals(ceLeft.Value))
                        queryBuilder.Append("true ");
                    else
                        visitExpression(expression.Right);
                    return true;
                }
                else if (ceRight != null && (ceRight.Type == typeof(bool) || ceRight.Type == typeof(bool?)))
                {
                    if (true.Equals(ceRight.Value))
                        queryBuilder.Append("true ");
                    else
                        visitExpression(expression.Left);
                    return true;
                }
            }
            return false;
        }
예제 #30
0
        private static bool CheckShortCircuitAnd(BinaryExpression expression, StringBuilder queryBuilder, Action<Expression> visitExpression)
        {
            if (expression.NodeType == ExpressionType.And || expression.NodeType == ExpressionType.AndAlso)
            {
                var ceLeft = expression.Left as ConstantExpression;
                var ceRight = expression.Right as ConstantExpression;

                if (ceLeft != null && ceLeft.Type == typeof(bool))
                {
                    if ((bool)ceLeft.Value)
                        visitExpression(expression.Right);
                    else
                        queryBuilder.Append("false ");
                    return true;
                }
                else if (ceRight != null && ceRight.Type == typeof(bool))
                {
                    if ((bool)ceRight.Value)
                        visitExpression(expression.Left);
                    else
                        queryBuilder.Append("false ");
                    return true;
                }
            }
            return false;
        }
예제 #31
0
 protected override LE.Expression VisitBinary(LE.BinaryExpression be, LE.Expression leftExpr, LE.Expression rightExpr)
 {
     if (be.NodeType == LE.ExpressionType.AndAlso || be.NodeType == LE.ExpressionType.OrElse)
     {
         return(LE.Expression.AndAlso(leftExpr, rightExpr));
     }
     return(base.VisitBinary(be, leftExpr, rightExpr));
 }
        public void CanConstantExpressionBeNull()
        {
            ConstantExpression c2 = Expression.Constant(null);
            ConstantExpression c1 = Expression.Constant(null);
            BinaryExpression   a  = Expression.Equal(c1, c2);

            Assert.Pass();
        }
예제 #33
0
        public static void Main()
        {
            // Numeric comparison
            var user1 = new User {
                Age = 13, Name = "Adam"
            };
            var user2 = new User {
                Age = 33, Name = "John"
            };
            var user3 = new User {
                Age = 53, Name = "DBag"
            };

            // Equal, NotEqual, GreaterThanOrEqual, GreaterThan, LessThan, LessThanOrEqual
            var rule = new Rule("Age", "LessThanOrEqual", "33");
            Func <User, bool> compiledRule = CompileUserRule <User>(rule);

            Console.WriteLine("Rule: " + rule.MemberName + " " + rule.Operator + " " + rule.TargetValue);
            Console.WriteLine("Evaluating Rule:");
            Console.WriteLine("\tuser1: Name: " + user1.Name + ", Age: " + user1.Age + " : " + compiledRule(user1));
            Console.WriteLine("\tuser2: Name: " + user2.Name + ", Age: " + user2.Age + " : " + compiledRule(user2));
            Console.WriteLine("\tuser3: Name: " + user3.Name + ", Age: " + user3.Age + " : " + compiledRule(user3));

            // Search within a string
            var mystring = new simpleString {
                searchValue = "I got ants!"
            };

            rule = new Rule("searchValue", "Contains", "ants");
            Func <simpleString, bool> compiledStringRule = CompileStringRule <simpleString>(rule);

            compiledStringRule = CompileStringRule <simpleString>(rule);

            Console.WriteLine("\nRule: " + rule.MemberName + " " + rule.Operator + " " + rule.TargetValue);
            Console.WriteLine("Evaluating Rule:");
            Console.WriteLine("\tsearchValue: \"" + mystring.searchValue + "\" : " + compiledStringRule(mystring));
            mystring.searchValue = "If you see something, say something.";
            Console.WriteLine("\tsearchValue: \"" + mystring.searchValue + "\" : " + compiledStringRule(mystring));

            // Dynamic rule creation and execution
            Console.WriteLine("\nDynamically constructed rule with simple math expression:");
            System.Linq.Expressions.BinaryExpression binaryExpression =
                System.Linq.Expressions.Expression.MakeBinary(
                    System.Linq.Expressions.ExpressionType.Divide,
                    System.Linq.Expressions.Expression.Constant(1000),
                    System.Linq.Expressions.Expression.Constant(20)
                    );
            Console.WriteLine("\tRule: " + binaryExpression.ToString());
            // Compile the expression.
            var compiledExpression = Expression.Lambda <Func <int> >(binaryExpression).Compile();

            // Execute the expression.
            Console.WriteLine("\tResult of rule execution: " + compiledExpression());

            Console.WriteLine("\nHit any key to exit");
            Console.ReadKey();
        }
예제 #34
0
            protected override Expression VisitBinary(System.Linq.Expressions.BinaryExpression node)
            {
                if (node.NodeType == ExpressionType.Equal && node.Method == null && node.Left.Type == typeof(XElement))
                {
                    return(Expression.Equal(this.Visit(node.Left), this.Visit(node.Right), node.IsLiftedToNull, methodInfoForAreEqual));
                }

                return(base.Visit(node));
            }
예제 #35
0
 private Expression Convert(
     LinqExp.BinaryExpression linqBinary,
     Func <Expression, Expression, MethodInfo, Expression> factory)
 {
     return(factory.Invoke(
                ConvertExp(linqBinary.Left),
                ConvertExp(linqBinary.Right),
                linqBinary.Method));
 }
예제 #36
0
        /// <summary>
        /// 表达式路由
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        string ExpressionRouter(System.Linq.Expressions.Expression exp)
        {
            //获取实体列的特性
            List <EntityPropColumnAttributes> columnAttrList = AttributeHelper.GetEntityColumnAtrributes <TEntity>();

            string sb = string.Empty;

            if (exp is System.Linq.Expressions.BinaryExpression)//二元运算符
            {
                System.Linq.Expressions.BinaryExpression be = ((System.Linq.Expressions.BinaryExpression)exp);
                return(BinarExpressionProvider(be.Left, be.Right, be.NodeType));
            }
            else if (exp is System.Linq.Expressions.MemberExpression)//成员
            {
                System.Linq.Expressions.MemberExpression me = ((System.Linq.Expressions.MemberExpression)exp);
                return(me.Member.Name);
            }
            else if (exp is System.Linq.Expressions.NewArrayExpression)//数组
            {
                System.Linq.Expressions.NewArrayExpression ae = ((System.Linq.Expressions.NewArrayExpression)exp);
                StringBuilder tmpstr = new StringBuilder();
                foreach (System.Linq.Expressions.Expression ex in ae.Expressions)
                {
                    tmpstr.Append(ExpressionRouter(ex));
                    tmpstr.Append(",");
                }
                return(tmpstr.ToString(0, tmpstr.Length - 1));
            }
            else if (exp is System.Linq.Expressions.MethodCallExpression)//方法
            {
                return(MethodExpression(exp));
            }
            else if (exp is System.Linq.Expressions.ConstantExpression)
            {
                System.Linq.Expressions.ConstantExpression ce = ((System.Linq.Expressions.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());
                    return(string.Format("{0}", ce.Value.ToString()));
                }
            }
            else if (exp is System.Linq.Expressions.UnaryExpression)
            {
                System.Linq.Expressions.UnaryExpression ue = ((System.Linq.Expressions.UnaryExpression)exp);
                return(ExpressionRouter(ue.Operand));
            }
            return(null);
        }
예제 #37
0
        public Expression Parse(Linq.Expression linqExpression)
        {
            if (linqExpression is Linq.ConstantExpression)
            {
                Linq.ConstantExpression cexpr = (Linq.ConstantExpression)linqExpression;

                if (!(cexpr.Value is double))
                {
                    throw new Exception("Can't parse a non-numeric constant");
                }

                return(new NumberExpression((double)cexpr.Value));
            }
            else if (linqExpression is Linq.ParameterExpression)
            {
                Linq.ParameterExpression pexpr = (Linq.ParameterExpression)linqExpression;
                return(new VariableExpression(pexpr.Name));
            }
            else if (linqExpression is Linq.MethodCallExpression)
            {
                Linq.MethodCallExpression mexpr = (Linq.MethodCallExpression)linqExpression;

                IList <Expression> arguments = new List <Expression>();

                foreach (Linq.Expression arg in mexpr.Arguments)
                {
                    arguments.Add(Parse(arg));
                }

                if (!exists(mexpr.Method))
                {
                    throw new Exception("Method name doesn't exist in the scope");
                }

                if (mexpr.Method.Equals(powMethod))
                {
                    return(new BinaryExpression(Binary.Power, arguments[0], arguments[1]));
                }

                string name = get(mexpr.Method);

                return(new FunctionExpression(name, arguments));
            }
            else if (linqExpression is Linq.BinaryExpression)
            {
                Linq.BinaryExpression bexpr = (Linq.BinaryExpression)linqExpression;

                Expression left  = Parse(bexpr.Left);
                Expression right = Parse(bexpr.Right);

                return(new BinaryExpression(getOperator(bexpr.NodeType), left, right));
            }

            throw new Exception("Can't parse expression");
        }
예제 #38
0
        protected override Linq.Expression VisitBinary(Linq.BinaryExpression node)
        {
            if (node.NodeType == Linq.ExpressionType.ArrayIndex)
            {
                _ = new ArrayIndex(this.Current)
                {
                    Array = this.VisitCacheParse(node.Left),
                    Index = this.VisitCacheParse(node.Right),
                };
            }
            else
            {
                Binary binary;

                if (node.IsReferenceComparison())
                {
                    if (node.NodeType == Linq.ExpressionType.Equal)
                    {
                        binary = new ReferenceEqual(this.Current);
                    }
                    else
                    {
                        binary = new ReferenceNotEqual(this.Current);
                    }
                }
                else
                {
                    binary = Binary.Create(this.Current, node.NodeType);

                    if (node.Method is MethodInfo method)
                    {
                        binary.Method = this.VisitMethod(method);
                    }

                    if (node.Conversion is LambdaExpression lambda)
                    {
                        binary.Conversion = new Lambda(this.VisitCache(lambda));
                    }

                    if (node.IsLiftedToNull)
                    {
                        binary.LiftToNull = true;
                    }
                }

                binary.Left  = this.VisitCacheParse(node.Left);
                binary.Right = this.VisitCacheParse(node.Right);
            }

            return(node);
        }
예제 #39
0
        /// <summary>
        /// 右边表达式路由
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        object RightExpressionRouter(System.Linq.Expressions.Expression exp)
        {
            string sb = string.Empty;

            if (exp is System.Linq.Expressions.BinaryExpression)
            {
                System.Linq.Expressions.BinaryExpression be = ((System.Linq.Expressions.BinaryExpression)exp);
                return(BinarExpressionProvider(be.Left, be.Right, be.NodeType));
            }
            else if (exp is System.Linq.Expressions.MethodCallExpression)//方法
            {
                return(MethodExpression(exp));
            }
            else
            {
                return(System.Linq.Expressions.Expression.Lambda(exp).Compile().DynamicInvoke());
            }
        }
예제 #40
0
        /// <summary>
        /// 获取Lambda表达式返回的结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func"></param>
        /// <returns></returns>
        public CoreFrameworkEntity GetLambdaEntity <T>(System.Linq.Expressions.Expression <Func <T, bool> > func)
        {
            listPara.Clear();
            CoreFrameworkEntity lambdaEntity = new CoreFrameworkEntity();

            // 二元运算符表达式
            if (func.Body is System.Linq.Expressions.BinaryExpression)
            {
                System.Linq.Expressions.BinaryExpression be = ((System.Linq.Expressions.BinaryExpression)func.Body);
                lambdaEntity.where    = BinarExpressionProvider(be.Left, be.Right, be.NodeType);
                lambdaEntity.paraList = listPara;
            }
            // 单纯的静态方法
            if (func.Body is System.Linq.Expressions.MethodCallExpression)
            {
                System.Linq.Expressions.MethodCallExpression be = ((System.Linq.Expressions.MethodCallExpression)func.Body);
                lambdaEntity.where    = ExpressionRouter(be);
                lambdaEntity.paraList = listPara;
            }
            return(lambdaEntity);
        }
예제 #41
0
        protected override Expression VisitBinary(System.Linq.Expressions.BinaryExpression node)
        {
            int currentTabs;

            if (tabs.Count > 0)
            {
                currentTabs = tabs[tabs.Count - 1];
                tabs.RemoveAt(tabs.Count - 1);
            }
            else
            {
                currentTabs = 0;
            }

            for (int i = 0; i < currentTabs; i++)
            {
                Console.Write("\t");
            }
            Console.WriteLine("VisitBinary {0}", node.NodeType.ToString());

            if (node.Right != null && (node.Right is System.Linq.Expressions.BinaryExpression ||
                                       node.Right is System.Linq.Expressions.ParameterExpression ||
                                       node.Right is System.Linq.Expressions.ConstantExpression))
            {
                tabs.Add(currentTabs + 1);
            }

            if (node.Left != null && (node.Left is System.Linq.Expressions.BinaryExpression ||
                                      node.Left is System.Linq.Expressions.ParameterExpression ||
                                      node.Left is System.Linq.Expressions.ConstantExpression))
            {
                tabs.Add(currentTabs + 1);
            }

            return(base.VisitBinary(node));
        }
        protected internal override Expression VisitBinary(BinaryExpression node)
        {
            if (node.NodeType == ExpressionType.ArrayIndex)
            {
                Visit(node.Left);
                Out('[');
                Visit(node.Right);
                Out(']');
            }
            else
            {
                string op;
                switch (node.NodeType)
                {
                // AndAlso and OrElse were unintentionally changed in
                // CLR 4. We changed them to "AndAlso" and "OrElse" to
                // be 3.5 compatible, but it turns out 3.5 shipped with
                // "&&" and "||". Oops.
                case ExpressionType.AndAlso:
                    op = "AndAlso";
                    break;

                case ExpressionType.OrElse:
                    op = "OrElse";
                    break;

                case ExpressionType.Assign:
                    op = "=";
                    break;

                case ExpressionType.Equal:
                    op = "==";
                    break;

                case ExpressionType.NotEqual:
                    op = "!=";
                    break;

                case ExpressionType.GreaterThan:
                    op = ">";
                    break;

                case ExpressionType.LessThan:
                    op = "<";
                    break;

                case ExpressionType.GreaterThanOrEqual:
                    op = ">=";
                    break;

                case ExpressionType.LessThanOrEqual:
                    op = "<=";
                    break;

                case ExpressionType.Add:
                case ExpressionType.AddChecked:
                    op = "+";
                    break;

                case ExpressionType.AddAssign:
                case ExpressionType.AddAssignChecked:
                    op = "+=";
                    break;

                case ExpressionType.Subtract:
                case ExpressionType.SubtractChecked:
                    op = "-";
                    break;

                case ExpressionType.SubtractAssign:
                case ExpressionType.SubtractAssignChecked:
                    op = "-=";
                    break;

                case ExpressionType.Divide:
                    op = "/";
                    break;

                case ExpressionType.DivideAssign:
                    op = "/=";
                    break;

                case ExpressionType.Modulo:
                    op = "%";
                    break;

                case ExpressionType.ModuloAssign:
                    op = "%=";
                    break;

                case ExpressionType.Multiply:
                case ExpressionType.MultiplyChecked:
                    op = "*";
                    break;

                case ExpressionType.MultiplyAssign:
                case ExpressionType.MultiplyAssignChecked:
                    op = "*=";
                    break;

                case ExpressionType.LeftShift:
                    op = "<<";
                    break;

                case ExpressionType.LeftShiftAssign:
                    op = "<<=";
                    break;

                case ExpressionType.RightShift:
                    op = ">>";
                    break;

                case ExpressionType.RightShiftAssign:
                    op = ">>=";
                    break;

                case ExpressionType.And:
                    op = IsBool(node) ? "And" : "&";
                    break;

                case ExpressionType.AndAssign:
                    op = IsBool(node) ? "&&=" : "&=";
                    break;

                case ExpressionType.Or:
                    op = IsBool(node) ? "Or" : "|";
                    break;

                case ExpressionType.OrAssign:
                    op = IsBool(node) ? "||=" : "|=";
                    break;

                case ExpressionType.ExclusiveOr:
                    op = "^";
                    break;

                case ExpressionType.ExclusiveOrAssign:
                    op = "^=";
                    break;

                case ExpressionType.Power:
                    op = "**";
                    break;     // This was changed in .NET Core from ^ to **

                case ExpressionType.PowerAssign:
                    op = "**=";
                    break;

                case ExpressionType.Coalesce:
                    op = "??";
                    break;

                default:
                    throw new InvalidOperationException();
                }

                Out('(');
                Visit(node.Left);
                Out(' ');
                Out(op);
                Out(' ');
                Visit(node.Right);
                Out(')');
            }
            return(node);
        }
예제 #43
0
        protected override System.Linq.Expressions.Expression VisitBinaryExpression(System.Linq.Expressions.BinaryExpression expression)
        {
            this.currentParts.Push(new StringBuilder());

            query.Append("(");

            VisitExpression(expression.Left);

            //bool localInverseActive = false;

            switch (expression.NodeType)
            {
            case ExpressionType.Equal:
                currentPart.Append("eq");
                break;

            case ExpressionType.NotEqual:
                currentPart.Append("ne");
                inverseMode = true;
                break;

            case ExpressionType.GreaterThan:
                currentPart.Append("gt");     //constant expression uses this to decide how to output the value
                break;

            case ExpressionType.GreaterThanOrEqual:
                currentPart.Append("ge");     //constant expression uses this to decide how to output the value
                break;

            case ExpressionType.LessThan:
                currentPart.Append("lt");     //constant expression uses this to decide how to output the value
                break;

            case ExpressionType.LessThanOrEqual:
                currentPart.Append("le");     //constant expression uses this to decide how to output the value
                break;

            case ExpressionType.AndAlso:
            case ExpressionType.And:
                query.Append(" AND ");
                break;

            case ExpressionType.OrElse:
            case ExpressionType.Or:
                query.Append(" OR ");
                break;

            case ExpressionType.Not:
                query.Append("");
                break;
            }
            bracketsEnabled = true;
            VisitExpression(expression.Right);
            inverseMode = false;
            //specific case where exact matches are required, we will insert the + or - at the start and a proximity of 0
            //may need to relocate this logic
            if (expression.Left is MemberExpression && expression.Right is ConstantExpression && ((ConstantExpression)expression.Right).Value is string)
            {
                if ((expression.NodeType == ExpressionType.NotEqual && !inverseMode) || (expression.NodeType == ExpressionType.Equal && inverseMode))
                {
                    query.Insert(query.Length - 2, " NOT ");
                }
                else
                {
                    currentPart.Insert(0, "+");
                }

                //currentPart.Insert(0, (expression.NodeType == ExpressionType.Equal) && !inverseMode || (
                //    (expression.NodeType == ExpressionType.NotEqual) & inverseMode & localInverseActive) ? "+" : "-");
            }

            //if (localInverseActive)
            //    inverseMode = !inverseMode;

            query.Append(currentPart);
            query.Append(")");
            currentParts.Pop();

            return(expression);
        }
예제 #44
0
 public BinaryExpressionProxy(BinaryExpression node)
 {
     ContractUtils.RequiresNotNull(node, nameof(node));
     _node = node;
 }
예제 #45
0
 protected virtual void VisitBinary(BinaryExpression binary)
 {
     Visit(binary.Left);
     Visit(binary.Right);
     Visit(binary.Conversion);
 }
예제 #46
0
 protected virtual Expression VisitBinary(BinaryExpression node)
 {
     throw new NotImplementedException();
 }
예제 #47
0
 /// <summary>
 /// 获得主键相等表达式
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 protected linq.Expression <Func <T, bool> > GetKeyEqualsExpression(T entity)
 {
     linq.BinaryExpression binary = linq.Expression.Equal(linq.Expression.Property(ParaModel, InfoKey), linq.Expression.Constant(GetKeyValue(entity)));
     return(linq.Expression.Lambda <Func <T, bool> >(binary, ParaModel));
 }
예제 #48
0
 private Expression ConvertImplicit(LinqExp.BinaryExpression linqBinary, Func <Expression, Expression, Expression> factory)
 {
     return(factory.Invoke(ConvertExp(linqBinary.Left), ConvertExp(linqBinary.Right)));
 }
예제 #49
0
 internal virtual Expression VisitComparison(BinaryExpression expression)
 {
     return(this.VisitBinary(EntityExpressionVisitor.RemoveUnnecessaryConverts(expression)));
 }
예제 #50
0
        protected internal override Expression VisitBinary(BinaryExpression node)
        {
            if (node.NodeType == ExpressionType.ArrayIndex)
            {
                ParenthesizedVisit(node, node.Left);
                Out("[");
                Visit(node.Right);
                Out("]");
            }
            else
            {
                bool parenthesizeLeft  = NeedsParentheses(node, node.Left);
                bool parenthesizeRight = NeedsParentheses(node, node.Right);

                string op;
                bool   isChecked = false;
                Flow   beforeOp  = Flow.Space;
                switch (node.NodeType)
                {
                case ExpressionType.Assign: op = "="; break;

                case ExpressionType.Equal: op = "=="; break;

                case ExpressionType.NotEqual: op = "!="; break;

                case ExpressionType.AndAlso: op = "&&"; beforeOp = Flow.NewLine; break;

                case ExpressionType.OrElse: op = "||"; beforeOp = Flow.NewLine; break;

                case ExpressionType.GreaterThan: op = ">"; break;

                case ExpressionType.LessThan: op = "<"; break;

                case ExpressionType.GreaterThanOrEqual: op = ">="; break;

                case ExpressionType.LessThanOrEqual: op = "<="; break;

                case ExpressionType.Add: op = "+"; break;

                case ExpressionType.AddAssign: op = "+="; break;

                case ExpressionType.AddAssignChecked: op = "+="; isChecked = true; break;

                case ExpressionType.AddChecked: op = "+"; isChecked = true; break;

                case ExpressionType.Subtract: op = "-"; break;

                case ExpressionType.SubtractAssign: op = "-="; break;

                case ExpressionType.SubtractAssignChecked: op = "-="; isChecked = true; break;

                case ExpressionType.SubtractChecked: op = "-"; isChecked = true; break;

                case ExpressionType.Divide: op = "/"; break;

                case ExpressionType.DivideAssign: op = "/="; break;

                case ExpressionType.Modulo: op = "%"; break;

                case ExpressionType.ModuloAssign: op = "%="; break;

                case ExpressionType.Multiply: op = "*"; break;

                case ExpressionType.MultiplyAssign: op = "*="; break;

                case ExpressionType.MultiplyAssignChecked: op = "*="; isChecked = true; break;

                case ExpressionType.MultiplyChecked: op = "*"; isChecked = true; break;

                case ExpressionType.LeftShift: op = "<<"; break;

                case ExpressionType.LeftShiftAssign: op = "<<="; break;

                case ExpressionType.RightShift: op = ">>"; break;

                case ExpressionType.RightShiftAssign: op = ">>="; break;

                case ExpressionType.And: op = "&"; break;

                case ExpressionType.AndAssign: op = "&="; break;

                case ExpressionType.Or: op = "|"; break;

                case ExpressionType.OrAssign: op = "|="; break;

                case ExpressionType.ExclusiveOr: op = "^"; break;

                case ExpressionType.ExclusiveOrAssign: op = "^="; break;

                case ExpressionType.Power: op = "**"; break;

                case ExpressionType.PowerAssign: op = "**="; break;

                //TODO: need to handle conversion lambda
                case ExpressionType.Coalesce: op = "??"; break;

                default:
                    throw new InvalidOperationException();
                }
                if (isChecked)
                {
                    Out(Flow.Break, "checked(", Flow.None);
                }


                if (parenthesizeLeft)
                {
                    Out("(", Flow.None);
                }
                Visit(node.Left);
                if (parenthesizeLeft)
                {
                    Out(Flow.None, ")", Flow.Break);
                }

                Out(beforeOp, op, Flow.Space | Flow.Break);

                if (parenthesizeRight)
                {
                    Out("(", Flow.None);
                }
                Visit(node.Right);
                if (parenthesizeRight)
                {
                    Out(Flow.None, ")", Flow.Break);
                }
            }
            return(node);
        }
예제 #51
0
        protected override Expression VisitBinary(BinaryExpression node)
        {
            base.VisitBinary(node);
            if (fieldMatchingOperators.TryGetValue(node.NodeType, out var fieldMatchingOperator))
            {
                var right      = stack.Pop();
                var left       = stack.Pop();
                var leftField  = left as FieldReferenceExpression;
                var leftValue  = left as ValueExpression;
                var rightField = right as FieldReferenceExpression;
                var rightValue = right as ValueExpression;
                if (leftValue != null && rightValue != null)
                {
                    throw new InvalidOperationException(
                              $"one of expression's sides should be field reference expression, [{node}]");
                }
                if (leftField != null && rightValue != null)
                {
                    if (rightValue.Value == null)
                    {
                        stack.Push(new IsEmptyExpression
                        {
                            Field = leftField,
                            Not   = fieldMatchingOperator == JqlFieldMatchingType.NotEquals
                        });
                    }
                    else
                    {
                        stack.Push(new FieldMatchingExpression
                        {
                            Field    = leftField,
                            Value    = rightValue,
                            Operator = fieldMatchingOperator
                        });
                    }
                }
                else if (leftValue != null && rightField != null)
                {
                    if (leftValue.Value == null)
                    {
                        stack.Push(new IsEmptyExpression
                        {
                            Field = rightField,
                            Not   = fieldMatchingOperator == JqlFieldMatchingType.NotEquals
                        });
                    }
                    else
                    {
                        stack.Push(new FieldMatchingExpression
                        {
                            Field    = rightField,
                            Value    = leftValue,
                            Operator = fieldMatchingOperator
                        });
                    }
                }
                else if (leftField != null && rightField != null && leftField.Source != rightField.Source)
                {
                    if (issueFunction.HasValue)
                    {
                        throw new InvalidOperationException(
                                  $"only one filter which defines the parent-child relationship is allowed, [{node}]");
                    }
                    var parent = FieldBySource(parentQuerySource, leftField, rightField);
                    var child  = FieldBySource(queryBuilder.Source, leftField, rightField);
                    if (parent == null || child == null)
                    {
                        throw new InvalidOperationException(
                                  $"at least one of the fields has an unsupported query source, [{node}]");
                    }
                    if (fieldMatchingOperator != JqlFieldMatchingType.Equals)
                    {
                        throw new InvalidOperationException(
                                  $"the parent-child relationship must be defined by [Equal] operator only, [{node}]");
                    }
                    if (string.Equals(parent.Field, "parent", StringComparison.InvariantCultureIgnoreCase))
                    {
                        issueFunction = JqlIssueFunction.SubTasksOf;
                    }
                    else if (string.Equals(child.Field, "parent", StringComparison.InvariantCultureIgnoreCase))
                    {
                        issueFunction = JqlIssueFunction.ParentsOf;
                    }
                    else
                    {
                        throw new InvalidOperationException(
                                  $"the parent-child relationship must be defined using [.Parent] field, [{node}]");
                    }
                }
                else if (leftField != null && rightField != null && leftField.Source == rightField.Source)
                {
                    throw new InvalidOperationException(
                              $"one of expression's sides should be constant expression, [{node}]");
                }
                else
                {
                    throw new InvalidOperationException($"unsupported binary expression, operator [{node.NodeType}]");
                }
            }
            else if (logicalOperators.TryGetValue(node.NodeType, out var logicalOperator))
            {
                var right = stack.Pop();
                var left  = stack.Pop();
                stack.Push(new Ast.BinaryExpression
                {
                    Left     = left,
                    Right    = right,
                    Operator = logicalOperator
                });
            }
            else
            {
                throw new InvalidOperationException($"unsupported binary expression, operator [{node.NodeType}]");
            }

            return(node);
        }
예제 #52
0
        private static SysLE.Expression SysExpressionWhere_Analyize(SysLE.Expression exp, StringBuilder builder)
        {
            if (exp == null)
            {
                return(null);
            }

            SysLE.BinaryExpression binEx = exp as SysLE.BinaryExpression;
            if (binEx != null)
            {
                SysExpressionWhere_Analyize(binEx.Left, builder);
            }

            switch (exp.NodeType)
            {
            case SysLE.ExpressionType.Parameter:
            {
                SysLE.ParameterExpression param = (SysLE.ParameterExpression)exp;
                builder.Append("(" + param.Name);
                return(null);
            }

            case SysLE.ExpressionType.MemberAccess:
            {
                SysLE.MemberExpression mexp = (SysLE.MemberExpression)exp;
                builder.Append("(" + mexp.Member.Name);
                return(null);
            }

            case SysLE.ExpressionType.Constant:
            {
                SysLE.ConstantExpression cex = (SysLE.ConstantExpression)exp;
                if (cex.Value is string)
                {
                    builder.Append("'" + cex.Value.ToString() + "') ");
                }
                else
                {
                    builder.Append(cex.Value.ToString() + ")");
                }
                return(null);
            }

            default:
            {
                if (exp.NodeType == SysLE.ExpressionType.Equal)
                {
                    builder.Append("=");
                }
                else if (exp.NodeType == SysLE.ExpressionType.NotEqual)
                {
                    builder.Append("<>");
                }
                else if (exp.NodeType == SysLE.ExpressionType.LessThan)
                {
                    builder.Append("<");
                }
                else if (exp.NodeType == SysLE.ExpressionType.LessThanOrEqual)
                {
                    builder.Append("<=");
                }
                else if (exp.NodeType == SysLE.ExpressionType.GreaterThan)
                {
                    builder.Append(">");
                }
                else if (exp.NodeType == SysLE.ExpressionType.GreaterThanOrEqual)
                {
                    builder.Append(">=");
                }
                else if (exp.NodeType == SysLE.ExpressionType.AndAlso || exp.NodeType == SysLE.ExpressionType.And)
                {
                    builder.Append("and");
                }
                else if (exp.NodeType == SysLE.ExpressionType.OrElse || exp.NodeType == SysLE.ExpressionType.Or)
                {
                    builder.Append("or");
                }
            }
            break;
            }

            if (binEx != null)
            {
                SysExpressionWhere_Analyize(binEx.Right, builder);
            }

            return(binEx);
        }