コード例 #1
0
ファイル: Expression.cs プロジェクト: MichaelHang/Math
 private static void CorrectExpression(ref ExpressionOperator oper, ref int num1, ref int num2, int resultMax)
 {
     switch (oper)
     {
     case ExpressionOperator.Add:
         if (num1 + num2 > resultMax)
         {
             oper = ExpressionOperator.Subtract;
             if (num1 < num2)
             {
                 int temp = num1;
                 num1 = num2;
                 num2 = temp;
             }
         }
         break;
     case ExpressionOperator.Subtract:
         if (num1 < num2)
         {
             int temp = num1;
             num1 = num2;
             num2 = temp;
         }
         break;
     case ExpressionOperator.Multiply:
         break;
     case ExpressionOperator.Divide:
         break;
     }
 }
コード例 #2
0
        protected internal ODataExpression(ODataExpression expression)
        {
            _functionCaller = expression._functionCaller;
            _left = expression._left;
            _right = expression._right;
            _operator = expression._operator;
            _conversionType = expression._conversionType;

            this.Reference = expression.Reference;
            this.ReferenceScope = expression.ReferenceScope;
            this.Value = expression.Value;
            this.Function = expression.Function;
        }
コード例 #3
0
ファイル: Expression.cs プロジェクト: MichaelHang/Math
        private static string OperatorToString(ExpressionOperator oper)
        {
            string strOper = "";
            switch (oper)
            {
            case ExpressionOperator.Add:
                strOper = "+";
                break;
            case ExpressionOperator.Subtract:
                strOper = "-";
                break;
            case ExpressionOperator.Multiply:
                strOper = "*";
                break;
            case ExpressionOperator.Divide:
                strOper = "/";
                break;
            }

            return strOper;
        }
コード例 #4
0
        private static string ConvertToWords(ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.Addition:
                return("Add");

            case ExpressionOperator.And:
                return("And");

            case ExpressionOperator.Constant:
                return("Constant");

            case ExpressionOperator.ConvertToInt32:
                return("Int32");

            case ExpressionOperator.ConvertToFloat32:
                return("Single");

            case ExpressionOperator.ConvertToFloat64:
                return("Double");

            case ExpressionOperator.ConvertToUInt16:
                return("UInt16");

            case ExpressionOperator.ConvertToUInt32:
                return("UInt32");

            case ExpressionOperator.ConvertToUInt8:
                return("UInt8");

            case ExpressionOperator.Division:
                return("Div");

            case ExpressionOperator.Equal:
                return("Eq");

            case ExpressionOperator.Equal_Obj:
                return("Eq_obj");

            case ExpressionOperator.GreaterEqualThan:
                return("Cge");

            case ExpressionOperator.GreaterEqualThan_Un:
                return("Cge_un");

            case ExpressionOperator.GreaterThan:
                return("Cgt");

            case ExpressionOperator.GreaterThan_Un:
                return("Cgt_un");

            case ExpressionOperator.LessEqualThan:
                return("Cle");

            case ExpressionOperator.LessEqualThan_Un:
                return("Cle_un");

            case ExpressionOperator.LessThan:
                return("Clt");

            case ExpressionOperator.LessThan_Un:
                return("Clt_un");

            case ExpressionOperator.LogicalAnd:
                return("And");

            case ExpressionOperator.LogicalNot:
                return("Not");

            case ExpressionOperator.LogicalOr:
                return("Or");

            case ExpressionOperator.Modulus:
                return("Rem");

            case ExpressionOperator.Multiplication:
                return("Mul");

            case ExpressionOperator.Not:
                return("Not");

            case ExpressionOperator.NotEqual:
                return("Neq");

            case ExpressionOperator.Or:
                return("Or");

            case ExpressionOperator.Xor:
                return("Xor");

            case ExpressionOperator.ShiftLeft:
                return("Shl");

            case ExpressionOperator.ShiftRight:
                return("Shr");

            case ExpressionOperator.SizeOf:
                return("Sizeof");

            case ExpressionOperator.Subtraction:
                return("Sub");

            case ExpressionOperator.UnaryMinus:
                return("Minus");

            case ExpressionOperator.Unknown:
                return("???");

            case ExpressionOperator.Variable:
                return("Var");

            case ExpressionOperator.WritableBytes:
                return("WB");

            default:
                return("???");
            }
        }
コード例 #5
0
ファイル: Expression.cs プロジェクト: jmptrader/Creek
 public static void Rule(Expression result, Expression expression, ExpressionOperator op, Term term)
 {
     result.Value = op.Function(expression.Value, term.Value);
 }
コード例 #6
0
ファイル: ExpressionInt.cs プロジェクト: njtromp/endless-ql
 /// <summary>
 /// Compares with expression
 /// </summary>
 /// <param name="expressionValue">Expression to compare with</param>
 /// <param name="op">Operator</param>
 /// <returns>Boolean expression</returns>
 public override TypedExpressionValue <bool> Compare(ExpressionValue expressionValue, ExpressionOperator op)
 {
     if (ValidCompare(expressionValue, op))
     {
         if (expressionValue.Type == typeof(double))
         {
             return(CompareValue(expressionValue as TypedExpressionValue <double>, op));
         }
         else if (expressionValue.Type == typeof(int))
         {
             return(CompareValue(expressionValue as ExpressionInt, op)); // Uses implicit cast
         }
     }
     throw new InvalidOperationException(UserMessages.ExceptionNoComparison(Type, expressionValue.Type, op));
 }
コード例 #7
0
 public ExpressionOperatorEntry(ExpressionOperator oper, int start, int end)
 {
     this.oper = oper;
     this.start = start;
     this.end = end;
     priority = -1;
 }
コード例 #8
0
 public ValueProcessor(List <string> operands, ExpressionOperator operators)
 {
     _operands  = operands;
     _operators = operators;
 }
コード例 #9
0
 public DefaultExpressionValuesAttribute(ExpressionOperator oper, double value)
 {
     Operator = oper;
     Value = value;
 }
コード例 #10
0
 public static void GetLeftRightOperatorsForBetween(bool includeLeft, bool includeRight
                                                    , out ExpressionOperator leftOp, out ExpressionOperator rightOp)
 {
     leftOp  = includeLeft ? ExpressionOperator.GreaterThanOrEquals : ExpressionOperator.GreaterThan;
     rightOp = includeRight ? ExpressionOperator.LessThanOrEquals : ExpressionOperator.LessThan;
 }
コード例 #11
0
 public abstract TypedExpressionValue <bool> Compare(ExpressionValue expressionValue, ExpressionOperator op);
コード例 #12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="fieldName"></param>
 /// <param name="expressionOperator"></param>
 /// <param name="fieldValue"></param>
 public FilterExpression(string fieldName, ExpressionOperator expressionOperator, string fieldValue)
 {
     FieldName          = fieldName;
     ExpressionOperator = expressionOperator;
     FieldValue         = fieldValue;
 }
コード例 #13
0
 /// <summary>
 /// Adds expression and operator to the respective chains
 /// </summary>
 /// <param name="expression">Expression to add</param>
 /// <param name="op">Operator to add</param>
 protected void AddToChain(Func <T> expression, ExpressionOperator op)
 {
     _expressionChain.Add(expression);
     _operatorChain.Add(op);
 }
コード例 #14
0
 public abstract ExpressionValue Combine(ExpressionValue expressionValue, ExpressionOperator op);
コード例 #15
0
 /// <summary>
 /// Checks if a comparison is possible
 /// </summary>
 /// <param name="expressionValue">Expression to compare with</param>
 /// <param name="op">Comparison operator</param>
 /// <returns>Is valid comparison</returns>
 protected bool ValidCompare(ExpressionValue expressionValue, ExpressionOperator op)
 {
     return(ExpressionOperators.Comparison.Contains(op) && CompatibleOperators.Contains(op));
 }
コード例 #16
0
 /// <summary>
 /// Checks if combination is possible
 /// </summary>
 /// <param name="expressionValue">Expression to combine with</param>
 /// <param name="op">Operators for expression</param>
 /// <returns>Is valid combination</returns>
 protected bool ValidCombine(ExpressionValue expressionValue, ExpressionOperator op)
 {
     return(CompatibleTypes.Contains(expressionValue.Type) && CompatibleOperators.Contains(op));
 }
コード例 #17
0
 /// <summary>
 /// Combine expressions with eachother
 /// </summary>
 /// <param name="expression1">Left hand side expression</param>
 /// <param name="expression2">Right hand side expression</param>
 /// <param name="op">Operator</param>
 /// <returns>Resulting expression</returns>
 protected abstract Func <T> CombineExpressions(Func <T> expression1, Func <T> expression2, ExpressionOperator op);
コード例 #18
0
 public static string ExceptionNoCombination(ExpressionType type1, ExpressionType type2, ExpressionOperator expressionOperator)
 {
     return(string.Format("Combination of {0} and {1} not implemented for operator {2}", type1, type2, expressionOperator));
 }
コード例 #19
0
        Expression IExpressionEncoder <Variable, Expression> .CompoundExpressionFor(ExpressionType type, ExpressionOperator op, Expression left, Expression right)
        {
            Contract.Ensures(Contract.Result <Expression>() != null);

            throw new System.NotImplementedException();
        }
コード例 #20
0
        public override TypedExpressionValue <bool> Compare(ExpressionValue expressionValue, ExpressionOperator op)
        {
            if (ValidCompare(expressionValue, op))
            {
                switch (expressionValue)
                {
                case IExpressionNumeric numericExpression:
                    return(NumericUtils.Compare(this, numericExpression, op));

                default:
                    throw new NotImplementedException();
                }
                throw new NotImplementedException();
            }
            throw new InvalidOperationException(UserMessages.ExceptionNoComparison(ExpressionType, expressionValue.ExpressionType, op));
        }
コード例 #21
0
 public override Interval ApplyConversion(ExpressionOperator conv, Interval intv)
 {
     return(Interval.ApplyConversion(conv, intv));
 }
コード例 #22
0
        /// <summary>
        /// Combines two expressions
        /// </summary>
        /// <param name="item1">Left hand side</param>
        /// <param name="item2">Right hand side</param>
        /// <param name="op">Operator</param>
        /// <returns>Resulting delegate</returns>
        protected override Func <double> CombineExpressions(Func <double> item1, Func <double> item2, ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.Plus:
                return(() => item1() + item2());

            case ExpressionOperator.Minus:
                return(() => item1() - item2());

            case ExpressionOperator.Multiply:
                return(() => item1() * item2());

            case ExpressionOperator.Divide:
                return(() => item1() / item2());
            }
            throw new InvalidOperationException(UserMessages.ExceptionNoCombination(Type, Type, op));
        }
コード例 #23
0
 /// <summary>
 ///     Creates a binary lambda expression that represents a comparison operation between a property
 ///     of <typeparamref name="T"/> and the provided value using the specified comparison operator.
 /// </summary>
 /// <typeparam name="T">
 ///     The type that contains the property to be compared.
 /// </typeparam>
 /// <param name="propertyInfo">
 ///     The metadata of the property to be compared.
 /// </param>
 /// <param name="value">
 ///     The value to compare the property.
 /// </param>
 /// <param name="operator">
 ///     The comparison operator.
 /// </param>
 /// <returns>A <see cref="Expression{TDelegate}"/> representing the comparison operation.</returns>
 public static Expression <Func <T, bool> > CreateBinary <T>(PropertyInfo propertyInfo, object value, ExpressionOperator @operator)
 {
     return(BuildBinaryExpression <T>(propertyInfo.Name, value, @operator));
 }
コード例 #24
0
 private static double CalculateOperator(ExpressionOperator op, double a, double b)
 {
     switch (op)
     {
         case ExpressionOperator.Equal:
             return a == b ? 1 : 0;
         case ExpressionOperator.NotEqual:
             return a != b ? 1 : 0;
         case ExpressionOperator.And:
             return a != 0 && b != 0 ? 1 : 0;                
         case ExpressionOperator.Div:
             {
                 if (b == 0) throw new Exception("Division by 0");
                 return a / b;
             }
         case ExpressionOperator.Greater:
             return a > b ? 1 : 0;
         case ExpressionOperator.Log:
             return Math.Log(b);
         case ExpressionOperator.Log10:
             return Math.Log10(b);
         case ExpressionOperator.Lower:
             return a < b ? 1 : 0;
         case ExpressionOperator.Minus:
             return a - b;
         case ExpressionOperator.Mult:
             return a * b;
         case ExpressionOperator.SignInversion:
             return -b;
         case ExpressionOperator.Or:
             return a != 0 || b != 0 ? 1 : 0;
         case ExpressionOperator.Plus:
             return a + b;
         case ExpressionOperator.Pow:
             return Math.Pow(a, b);
         case ExpressionOperator.Sign:
             return Math.Sign(b);
         case ExpressionOperator.Cos:
             return Math.Cos(b);
         case ExpressionOperator.Sin:
             return Math.Sin(b);
         case ExpressionOperator.Tan:
             return Math.Tan(b);
         case ExpressionOperator.ReplaceNil:
             return a == 0 ? b : a;
         case ExpressionOperator.Negate:
             return b == 0 ? 1 : 0;
     }
     return 0;
 }
コード例 #25
0
 /// <summary>
 ///     Creates a binary lambda expression that represents a comparison operation between a property
 ///     of <typeparamref name="T"/> and the provided value using the specified comparison operator.
 /// </summary>
 /// <typeparam name="T">
 ///     The type that contains the property to be compared.
 /// </typeparam>
 /// <param name="propertyNameOrPath">
 ///     The name or the path to the property.
 /// </param>
 /// <param name="value">
 ///     The value to compare the property.
 /// </param>
 /// <param name="operator">
 ///     The comparison operator.
 /// </param>
 /// <returns>A <see cref="Expression{TDelegate}"/> representing the comparison operation.</returns>
 public static Expression <Func <T, bool> > CreateBinary <T>(string propertyNameOrPath, object value, ExpressionOperator @operator)
 {
     return(BuildBinaryExpression <T>(propertyNameOrPath, value, @operator));
 }
コード例 #26
0
 public static string GetOperatorString(ExpressionOperator oper)
 {
     if (!operatorString.ContainsKey(oper))
         return null;
     return operatorString[oper];
 }
コード例 #27
0
        public override TypedExpressionValue <bool> Compare(ExpressionValue expressionValue, ExpressionOperator op)
        {
            if (ValidCompare(expressionValue, op))
            {
                ExpressionBool expression;
                switch (expressionValue.ExpressionType)
                {
                case ExpressionType.Bool:
                    expression = expressionValue as ExpressionBool;
                    break;

                default:
                    throw new NotImplementedException();
                }

                AddToChain(expression.GetExpression(), op);
                UsedIdentifiers = CombineElements(expressionValue);
                return(this);
            }
            throw new InvalidOperationException(UserMessages.ExceptionNoComparison(ExpressionType, expressionValue.ExpressionType, op));
        }
コード例 #28
0
        /// <summary>
        /// parse an sql query text
        /// </summary>
        /// <param name="query">sql query text</param>
        /// <param name="validator">sql query validator against a database</param>
        /// <returns></returns>
        public static DbQuery Parse(string query, IQueryValidation validator)
        {
            if (validator == null)
            {
                throw new ArgumentException("No query database validator provided");
            }

            int           top             = -1;
            ColumnsSelect columnSelect    = null;
            var           tableCollection = new List <Table>();
            SqlJoin       join            = null;

            ExpressionOperator where = null;

            TokenItem PreviousToken    = default(TokenItem);
            TokenItem CurrentToken     = default(TokenItem);
            var       peekedToken      = default(TokenItem);
            var       columnCollection = new List <Column>();
            Table     joinTable        = null;

            var queue = new Queue <TokenItem>(ParseTokens(query));

//#if DEBUG
//			Console.WriteLine("Query tokens:");
//			Console.WriteLine($"  {String.Join($"{Environment.NewLine}  ", queue)}{Environment.NewLine}");
//#endif

            bool EndOfStream = queue.Count == 0;

            IEnumerable <Table> AllTables()
            {
                foreach (var t in tableCollection)
                {
                    yield return(t);
                }
                if (joinTable != null)
                {
                    yield return(joinTable);
                }
            }

            bool GetToken()
            {
                if (EndOfStream || (EndOfStream = !queue.TryDequeue(out TokenItem tk)))
                {
                    return(false);
                }
                //save previous
                PreviousToken = CurrentToken;
                //get current
                CurrentToken = tk;

                return(true);
            }

            bool PeekToken()
            {
                if (!EndOfStream && queue.TryPeek(out peekedToken))
                {
                    return(true);
                }
                return(false);
            }

            bool GetTokenIf(TokenType token)
            {
                if (!EndOfStream && queue.TryPeek(out peekedToken) && peekedToken.Token == token)
                {
                    CurrentToken = queue.Dequeue();
                    return(true);
                }
                return(false);
            };

            bool GetTokenIfContains(List <TokenType> tokens)
            {
                if (!EndOfStream && queue.TryPeek(out peekedToken) && tokens.Contains(peekedToken.Token))
                {
                    CurrentToken = queue.Dequeue();
                    return(true);
                }
                return(false);
            }

            Column ReadColumnName(bool readAS = true)
            {
                Column selectColumn = null;

                //read operand [(i).](column)
                if (GetTokenIf(TokenType.Identifier))
                {
                    var    tableAlias  = CurrentToken.Value;
                    String columnName  = null;
                    String columnAlias = null;

                    if (GetTokenIf(TokenType.Dot))
                    {
                        if (!GetToken())
                        {
                            throw new ArgumentException($"column name expected");
                        }
                        columnName = CurrentToken.Value;
                    }
                    else
                    {
                        columnName = tableAlias;
                        tableAlias = null;
                    }
                    //alias
                    if (readAS && GetTokenIf(TokenType.AS))
                    {
                        if (!GetTokenIf(TokenType.Identifier))
                        {
                            throw new ArgumentException($"Column alias name expected after AS: {CurrentToken.Value}");
                        }
                        columnAlias = CurrentToken.Value;
                    }
                    selectColumn = new Column(columnName, tableAlias, columnAlias);
                }

                return(selectColumn);
            }

            ExpressionOperand ReadOperand(DbColumnType casting)
            {
                if (!PeekToken())
                {
                    return(null);
                }

                switch (peekedToken.Token)
                {
                case TokenType.String:
                    GetToken();
                    return(new StringOperand(CurrentToken.Value));

                case TokenType.Number:
                    GetToken();
                    return(new NumberOperand(CurrentToken.Value, casting));

                case TokenType.Identifier:
                    //get column name
                    GetToken();
                    var columnName = CurrentToken.Value;
                    var position   = CurrentToken.Position;

                    String columnIdentifier = null;

                    if (GetTokenIf(TokenType.Dot))
                    {
                        //tablealias.colummname
                        if (!GetToken())
                        {
                            throw new ArgumentException($"column name expected");
                        }
                        columnIdentifier = columnName;
                        columnName       = CurrentToken.Value;
                    }

                    Column col = null;
                    //try to find column in known tables
                    if (columnIdentifier != null)
                    {
                        //find in table by its alias
                        var aliasTable = AllTables().FirstOrDefault(t => t.Alias == columnIdentifier);
                        if (aliasTable == null)
                        {
                            throw new ArgumentException($"cannot find column: {columnName}");
                        }
                        col      = new Column(columnName, aliasTable.Alias);
                        col.Meta = validator.ColumnMetadata(aliasTable.Name, col.Name);
                    }
                    else
                    {
                        //find the only first in all known tables
                        var tables = AllTables().Where(t => validator.TableHasColumn(t.Name, columnName)).ToList();
                        if (tables.Count != 1)
                        {
                            throw new ArgumentException($"column: {columnName} could not be found in database or cannot resolve multiple tables");
                        }
                        //tableName = tables[0].Name;
                        col = new Column(columnName, validator.ColumnMetadata(tables[0].Name, columnName));
                    }

                    return(new ColumnOperand(col, casting));

                default:
                    return(null);
                }
            }

            ExpressionOperator ReadExpression()
            {
                //https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form

                var stack     = new Stack <ExpressionItem>();
                var operStack = new Stack <TokenType>();

                ExpressionItem BuildTree()
                {
                    //get higher precedence operator from operator stack
                    var oper = operStack.Pop();

                    //get left and right expressions
                    var right = stack.Pop();
                    var left  = stack.Pop();

                    //create new expression
                    var expr = ExpressionOperator.Create(left, oper, right);

                    //push onto expression stack
                    stack.Push(expr);

                    return(expr);
                }

                var end = false;

                while (!end)
                {
                    if (!(end = !PeekToken()))
                    {
                        var currOper = peekedToken.Token;
                        switch (currOper)
                        {
                        case TokenType.String:
                        case TokenType.Number:
                        case TokenType.Identifier:
                            //if on top of stack there's a casting oper, apply it
                            DbColumnType casting = DbColumnType.None;
                            if (stack.Count > 0 && stack.Peek().ExpressionType == ExpressionItemType.Casting)
                            {
                                casting = (stack.Pop() as CastingExpression).Type;
                            }
                            //read operand and apply casting if any
                            stack.Push(ReadOperand(casting));
                            break;

                        case TokenType.OpenPar:
                            //consume the open parenthesis (
                            GetToken();
                            //try ahead if it's a casting operator
                            var currToken = CurrentToken.Token;

                            //try to get ahead a casting type
                            if (PeekToken() && (casting = peekedToken.Token.ToCast()).IsCasting())
                            {
                                //consume the casting type
                                GetToken();

                                if (!GetTokenIf(TokenType.ClosePar))
                                {
                                    throw new ArgumentException("close parenthesis expected after casting type");
                                }
                                //store new casting expression
                                stack.Push(new CastingExpression(casting));
                            }
                            else
                            {
                                operStack.Push(currToken);
                            }
                            break;

                        case TokenType.ClosePar:                                 //  )
                            GetToken();
                            while (operStack.Count > 0 && operStack.Peek() != TokenType.OpenPar)
                            {
                                BuildTree();
                            }
                            //discard close parenthesis ) operator
                            operStack.Pop();
                            break;

                        default:
                            //operator
                            // AND  OR  == <>  >  >=  <  <=
                            if (currOper == TokenType.AND || currOper == TokenType.OR ||
                                currOper == TokenType.Equal || currOper == TokenType.NotEqual ||
                                currOper == TokenType.Greater || currOper == TokenType.GreaterOrEqual ||
                                currOper == TokenType.Less || currOper == TokenType.LessOrEqual)
                            {
                                GetToken();

                                var thisOper = CurrentToken.Token;

                                //build tree of all operator on stack with higher precedence than current
                                while (operStack.Count > 0 &&
                                       Precedence(operStack.Peek()) < Precedence(thisOper))
                                {
                                    BuildTree();
                                }
                                //
                                operStack.Push(thisOper);
                            }
                            else
                            {
                                throw new ArgumentException($"operator expected, and we got: {currOper}");
                            }
                            break;
                        }
                    }
                }

                //resolve left operator
                while (operStack.Count > 0)
                {
                    BuildTree();
                }

                if (stack.Count == 0)
                {
                    return(null);
                }
                var item = stack.Pop();

                if (item.ExpressionType != ExpressionItemType.Operator)
                {
                    throw new ArgumentException("operator expected on expression");
                }
                return(item as ExpressionOperator);
            }

            int Precedence(TokenType token)
            {
                switch (token)
                {
                //case TokenType.NOT: // ~ BITWISE NOT
                //	return 1;
                case TokenType.Astherisk:                         // *  / %(modulus)
                    return(2);

                case TokenType.Plus:                       // + - sign
                case TokenType.Minus:                      // + addition, concatenation    -substraction
                    return(3);                             //          bitwise & AND, | OR |

                case TokenType.Equal:                      //comparison operators
                case TokenType.NotEqual:
                case TokenType.Greater:
                case TokenType.GreaterOrEqual:
                case TokenType.Less:
                case TokenType.LessOrEqual:
                    return(4);

                case TokenType.NOT:
                    return(5);

                case TokenType.AND:
                    return(6);

                case TokenType.BETWEEN:                         //ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
                case TokenType.IN:
                case TokenType.LIKE:
                case TokenType.OR:
                    return(7);

                case TokenType.Assign:
                    return(8);

                case TokenType.OpenPar:
                    //highest
                    return(16);

                default:
                    return(0);
                }
            }

            #region SELECT

            if (!GetTokenIf(TokenType.SELECT))
            {
                throw new ArgumentException("SELECT expected");
            }

            //see if it's a function
            if (GetTokenIfContains(SelectFunctions))
            {
                var function = CurrentToken.Token;

                if (!GetTokenIf(TokenType.OpenPar))
                {
                    throw new ArgumentException($"expected ( after FUNCTION {CurrentToken.Token}");
                }

                // COUNT([(i).](column))
                var functionColumn = ReadColumnName(readAS: false);

                if (!GetTokenIf(TokenType.ClosePar))
                {
                    throw new ArgumentException($"expected ) closing {CurrentToken.Token}");
                }

                //alias
                String functionColumnAlias = null;
                if (GetTokenIf(TokenType.AS))
                {
                    if (!GetTokenIf(TokenType.Identifier))
                    {
                        throw new ArgumentException($"");
                    }
                    functionColumnAlias = CurrentToken.Value;
                }
                columnSelect = new ColumnsSelect(function, functionColumn, functionColumnAlias);
            }
            else
            {
                //preceded by TOP if any
                //TOP integer PERCENT
                if (GetTokenIf(TokenType.TOP))
                {
                    if (!GetTokenIf(TokenType.Number))
                    {
                        throw new ArgumentException($"Number expected after TOP");
                    }
                    //test for integer
                    if (!int.TryParse(CurrentToken.Value, out top) || top <= 0)
                    {
                        throw new ArgumentException($"TOP [positive integer greater than 0] expected: {CurrentToken.Value}");
                    }
                    //PERCENT
                    if (GetTokenIf(TokenType.PERCENT))
                    {
                        //save if for later
                    }
                }

                //read columns
                //read column selector: comma separated or *
                if (GetTokenIf(TokenType.Astherisk))
                {
                    columnSelect = new ColumnsSelect(top);
                }
                else
                {
                    //mut have at least one column identifier
                    if (PeekToken() && peekedToken.Token != TokenType.Identifier)
                    {
                        throw new ArgumentException("table column name(s) expected");
                    }

                    //read first
                    columnCollection.Add(ReadColumnName());

                    while (GetTokenIf(TokenType.Comma))
                    {
                        //next
                        columnCollection.Add(ReadColumnName());
                    }
                    columnSelect = new ColumnsSelect(top, columnCollection);
                }
            }

            #endregion

            #region FROM

            if (!GetTokenIf(TokenType.FROM))
            {
                throw new ArgumentException("FROM expected");
            }

            do
            {
                //read identifier: table name
                if (!GetTokenIf(TokenType.Identifier))
                {
                    throw new ArgumentException("table name identifier after FROM expected");
                }

                var    tableName  = CurrentToken.Value;
                String tableAlias = null;

                //var pos = CurrentToken.Position;
                // [table name] AS [alias]
                if (GetTokenIf(TokenType.AS))
                {
                    //create it so WHERE can handle it
                    //tableIdentifier = new DbQueryTableIdentifier(table, CurrentToken.Value);
                    if (!GetTokenIf(TokenType.Identifier))
                    {
                        throw new ArgumentException($"Table alias expected after AS");
                    }
                    tableAlias = CurrentToken.Value;
                }
                //tableIdentifier = new DbQueryTableIdentifier(table);
                var table = new Table(tableName, tableAlias);

                if (!validator.HasTable(table.Name))
                {
                    throw new ArgumentException($"Invalid table name: {table.Name}");
                }

                tableCollection.Add(table);
            }while (GetTokenIf(TokenType.Comma));

            if (columnSelect.FullColumns)
            {
                //fill SELECT * with all columns in FROM if applies
                foreach (var col in tableCollection
                         .SelectMany(
                             table => validator.ColumnsOf(table.Name),
                             (table, col) => new Column(col, validator.ColumnMetadata(table.Name, col))))
                {
                    columnSelect.Add(col);
                }
            }
            else
            {
                //check all SELECT columns
                foreach (var col in columnSelect.Columns)
                {
                    string tableName = null;

                    if (col.HasTableAlias)
                    {
                        //find it in table collection
                        var table = tableCollection.FirstOrDefault(t => t.HasAlias && col.TableAlias == t.Alias);
                        if (table == null)
                        {
                            throw new ArgumentException($"column alias undefined {col}");
                        }
                        tableName = table.Name;
                        if (!validator.TableHasColumn(tableName, col.Name))
                        {
                            throw new ArgumentException($"column: {col.Name} could not be found in table {tableName}");
                        }
                    }
                    else
                    {
                        //brute force search
                        var tables = tableCollection.Where(t => validator.TableHasColumn(t.Name, col.Name)).ToList();
                        if (tables.Count != 1)
                        {
                            throw new ArgumentException($"column: {col.Name} could not be found in database or cannot resolve multiple tables");
                        }
                        tableName = tables[0].Name;
                    }
                    //link column to table, and find its index
                    col.Meta = validator.ColumnMetadata(tableName, col.Name);
                }
            }

            #endregion

            #region JOIN

            if (GetTokenIfContains(JoinStarts))
            {
                //FROM table must has identifier, should be only one here

                TokenType          JoinCommand    = CurrentToken.Token;
                ComparisonOperator JoinExpression = null;

                if (CurrentToken.Token == TokenType.LEFT || CurrentToken.Token == TokenType.RIGHT ||
                    CurrentToken.Token == TokenType.FULL)
                {
                    //LEFT OUTER JOIN
                    //RIGHT OUTER JOIN
                    //FULL OUTER JOIN
                    if (!GetTokenIf(TokenType.OUTER))
                    {
                        throw new ArgumentException($"OUTER expected after {CurrentToken.Token}");
                    }
                }
                else if (!(CurrentToken.Token == TokenType.INNER || CurrentToken.Token == TokenType.CROSS))
                {
                    //INNER JOIN
                    //CROSS JOIN
                    throw new ArgumentException($"invalid JOIN keyword {CurrentToken.Token}");
                }

                if (!GetTokenIf(TokenType.JOIN))
                {
                    throw new ArgumentException($"JOIN expected after {CurrentToken.Token}");
                }

                //read table name
                if (!GetTokenIf(TokenType.Identifier))
                {
                    throw new ArgumentException("table name identifier after FROM expected");
                }
                //check -table name
                var    tableName  = CurrentToken.Value;
                String tableAlias = null;

                // + identifier
                if (GetTokenIf(TokenType.AS))
                {
                    if (!GetTokenIf(TokenType.Identifier))
                    {
                        throw new ArgumentException($"Table alias expected after AS");
                    }
                    tableAlias = CurrentToken.Value;
                }
                joinTable = new Table(tableName, tableAlias);

                if (!validator.HasTable(joinTable.Name))
                {
                    throw new ArgumentException($"Invalid table name: {joinTable.Name}");
                }

                //read ON
                if (!GetTokenIf(TokenType.ON))
                {
                    throw new ArgumentException($"ON expected in JOIN query");
                }

                //read expression
                //left & right operand must be from different tables
                //read left
                var left = ReadOperand(DbColumnType.None);

                //read operator
                if (!GetToken() || !CurrentToken.Token.IsOperator())
                {
                    throw new ArgumentException("operator of JOIN expression expected");
                }
                var oper = CurrentToken;

                //read right
                var right = ReadOperand(DbColumnType.None);

                //operands must be of type column with different table identifiers
                if (!left.IsColumn ||
                    !right.IsColumn ||
                    ((ColumnOperand)left).Column.TableAlias == ((ColumnOperand)right).Column.TableAlias)
                {
                    throw new ArgumentException("JOIN query expression table identifiers cannot be the same");
                }

                JoinExpression = new ComparisonOperator(
                    left,
                    oper.Token,
                    right
                    );
                join = new SqlJoin(JoinCommand, joinTable, JoinExpression);

                //validate JOIN column tables
            }

            #endregion

            #region WHERE if any

            if (GetTokenIf(TokenType.WHERE))
            {
                if ((where = ReadExpression()) == null)
                {
                    throw new ArgumentException("WHERE expression(s) expected");
                }
            }

            #endregion

            if (GetToken() && CurrentToken.Token != TokenType.SemiColon)
            {
                throw new ArgumentException($"Unexpected: {CurrentToken.Value} @ {CurrentToken.Position}");
            }

            return(new DbQuery(columnSelect, tableCollection, join, new ColumnsWhere(where)));
        }
コード例 #29
0
 protected ODataExpression(ODataExpression left, ODataExpression right, ExpressionOperator expressionOperator)
 {
     _left     = left;
     _right    = right;
     _operator = expressionOperator;
 }
コード例 #30
0
ファイル: ExpressionInt.cs プロジェクト: njtromp/endless-ql
        /// <summary>
        /// Combines two expressions
        /// </summary>
        /// <param name="item1">Left hand side</param>
        /// <param name="item2">Right hand side</param>
        /// <param name="op">Operator</param>
        /// <returns>Resulting delegate</returns>
        protected override Func <int> CombineExpressions(Func <int> item1, Func <int> item2, ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.Plus:
                return(() => item1() + item2());

            case ExpressionOperator.Minus:
                return(() => item1() - item2());

            case ExpressionOperator.Multiply:
                return(() => item1() * item2());

            case ExpressionOperator.Divide:
                return(() => item1() / item2());
            }
            throw new NotImplementedException();
        }
コード例 #31
0
 private FilterExpression(FilterExpression left, FilterExpression right, ExpressionOperator expressionOperator)
 {
     _left = left;
     _right = right;
     _operator = expressionOperator;
 }
コード例 #32
0
ファイル: ExpressionInt.cs プロジェクト: njtromp/endless-ql
        /// <summary>
        /// Compares expression with double expression
        /// </summary>
        /// <param name="item">double expression</param>
        /// <param name="op">Compare operator</param>
        /// <returns>Boolean expression</returns>
        private TypedExpressionValue <bool> CompareValue(TypedExpressionValue <double> item, ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.GreaterThan:
                return(new ExpressionBool(CombineWidgets(item), () => { return Result > item.Result; }));

            case ExpressionOperator.GreaterEquals:
                return(new ExpressionBool(CombineWidgets(item), () => { return Result >= item.Result; }));

            case ExpressionOperator.LessThan:
                return(new ExpressionBool(CombineWidgets(item), () => { return Result < item.Result; }));

            case ExpressionOperator.LessEquals:
                return(new ExpressionBool(CombineWidgets(item), () => { return Result <= item.Result; }));

            case ExpressionOperator.Equals:
                return(new ExpressionBool(CombineWidgets(item), () => { return Result == item.Result; }));
            }
            throw new InvalidOperationException(UserMessages.ExceptionNoComparison(Type, item.Type, op));
        }
コード例 #33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fieldName"></param>
 /// <param name="expressionOperator"></param>
 /// <param name="fieldValue"></param>
 public FilterExpression(string fieldName, ExpressionOperator expressionOperator, string fieldValue)
 {
     FieldName = fieldName;
     ExpressionOperator = expressionOperator;
     FieldValue = fieldValue;
 }
コード例 #34
0
        /// <returns>
        /// A (textual representation of the) C# operator for <code>op</code>
        /// </returns>
        public static string ToString(ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.Addition:
                return("+");

            case ExpressionOperator.And:
                return("&");

            case ExpressionOperator.Constant:
                return("<CONST>");

            case ExpressionOperator.ConvertToInt32:
                return("(Int32)");

            case ExpressionOperator.ConvertToUInt16:
                return("(UInt16)");

            case ExpressionOperator.ConvertToUInt32:
                return("(UInt32)");

            case ExpressionOperator.ConvertToUInt8:
                return("(UInt8)");

            case ExpressionOperator.ConvertToFloat32:
                return("(Single)");

            case ExpressionOperator.ConvertToFloat64:
                return("(Double)");

            case ExpressionOperator.Division:
                return("/");

            case ExpressionOperator.Equal:
                return("==");

            case ExpressionOperator.Equal_Obj:
                return("=Equals=");

            case ExpressionOperator.GreaterEqualThan:
                return(">=");

            case ExpressionOperator.GreaterEqualThan_Un:
                return(">=_un");

            case ExpressionOperator.GreaterThan:
                return(">");

            case ExpressionOperator.GreaterThan_Un:
                return(">_un");

            case ExpressionOperator.LessEqualThan:
                return("<=");

            case ExpressionOperator.LessEqualThan_Un:
                return("<=_un");

            case ExpressionOperator.LessThan:
                return("<");

            case ExpressionOperator.LessThan_Un:
                return("<_un");

            case ExpressionOperator.LogicalAnd:
                return("&&");

            case ExpressionOperator.LogicalNot:
                return("!");

            case ExpressionOperator.LogicalOr:
                return("||");

            case ExpressionOperator.Modulus:
                return("%");

            case ExpressionOperator.Multiplication:
                return("*");

            case ExpressionOperator.Not:
                return("!");

            case ExpressionOperator.NotEqual:
                return("!=");

            case ExpressionOperator.Or:
                return("|");

            case ExpressionOperator.Xor:
                return("^");

            case ExpressionOperator.ShiftLeft:
                return("<<");

            case ExpressionOperator.ShiftRight:
                return(">>");

            case ExpressionOperator.SizeOf:
                return("sizeof");

            case ExpressionOperator.Subtraction:
                return("-");

            case ExpressionOperator.UnaryMinus:
                return("-");

            case ExpressionOperator.Unknown:
                return("<???>");

            case ExpressionOperator.Variable:
                return("<VAR>");

            case ExpressionOperator.WritableBytes:
                return("<WritableBytes>");

            default:
                return("<????>");
            }
        }
コード例 #35
0
 public abstract TInterval ApplyConversion(ExpressionOperator conv, TInterval intv);
コード例 #36
0
 protected DynamicODataExpression(ODataExpression left, ODataExpression right, ExpressionOperator expressionOperator)
     : base(left, right, expressionOperator)
 {
 }
コード例 #37
0
    private int processOperator(string expression, int originalOperatorIndex, Operator originalOperator, Stack operatorStack, Stack operandStack, bool haveOperand, Operator unaryOperator)
    {
        int      operatorIndex = originalOperatorIndex;
        Operator @operator     = originalOperator;


        if (haveOperand && @operator is OpenParenthesesOperator)
        {
            NextOperator nextOperator = processFunction(expression, operatorIndex, operandStack);

            @operator     = nextOperator.Operator;
            operatorIndex = nextOperator.Index + @operator.Length;

            nextOperator = getNextOperator(expression, operatorIndex, null);

            if (nextOperator != null)
            {
                @operator     = nextOperator.Operator;
                operatorIndex = nextOperator.Index;
            }
            else
            {
                return(operatorIndex);
            }
        }


        if (@operator is OpenParenthesesOperator)
        {
            ExpressionOperator expressionOperator = new ExpressionOperator(@operator, unaryOperator);
            operatorStack.Push(expressionOperator);
        }
        else if (@operator is ClosedParenthesesOperator)
        {
            ExpressionOperator stackOperator = null;

            if (operatorStack.Count > 0)
            {
                stackOperator = (ExpressionOperator)operatorStack.Peek();
            }

            // Process until we reach an open parentheses.
            while (stackOperator != null && !(stackOperator.Operator is OpenParenthesesOperator))
            {
                processTree(operandStack, operatorStack);

                if (operatorStack.Count > 0)
                {
                    stackOperator = (ExpressionOperator)operatorStack.Peek();
                }
                else
                {
                    stackOperator = null;
                }
            }

            if (operatorStack.Count == 0)
            {
                throw new EvaluationException("Expression is invalid.");
            }

            ExpressionOperator expressionOperator = (ExpressionOperator)operatorStack.Pop();

            if (!(expressionOperator.Operator is OpenParenthesesOperator))
            {
                throw new EvaluationException("Expression is invalid.");
            }

            // Process the unary operator if we have one.
            if (expressionOperator.UnaryOperator != null)
            {
                object operand = operandStack.Pop();

                ExpressionTree tree = new ExpressionTree(this, operand, null, null, expressionOperator.UnaryOperator);

                operandStack.Push(tree);
            }
        }
        else
        {
            // Process non-param operator.
            if (operatorStack.Count > 0)
            {
                ExpressionOperator stackOperator = (ExpressionOperator)operatorStack.Peek();

                while (stackOperator != null && stackOperator.Operator.Precedence >= @operator.Precedence)
                {
                    processTree(operandStack, operatorStack);

                    if (operatorStack.Count > 0)
                    {
                        stackOperator = (ExpressionOperator)operatorStack.Peek();
                    }
                    else
                    {
                        stackOperator = null;
                    }
                }
            }

            ExpressionOperator expressionOperator = new ExpressionOperator(@operator, unaryOperator);

            operatorStack.Push(expressionOperator);
        }


        int rtnCtr = operatorIndex + @operator.Length;

        return(rtnCtr);
    }
コード例 #38
0
ファイル: Expression.cs プロジェクト: Slesa/Lingua
 public static void Rule(Expression result,  Expression expression,  ExpressionOperator op, Term term)
 {
     result.Value = op.Function(expression.Value, term.Value);
 }
コード例 #39
0
ファイル: ExpressionBool.cs プロジェクト: njtromp/endless-ql
 /// <summary>
 /// Compares with expression
 /// </summary>
 /// <param name="expressionValue">Expression to compare with</param>
 /// <param name="op">Operator</param>
 /// <returns>Boolean expression</returns>
 public override TypedExpressionValue <bool> Compare(ExpressionValue expressionValue, ExpressionOperator op)
 {
     if (ValidCompare(expressionValue, op))
     {
         if (expressionValue.Type == typeof(bool))
         {
             AddToChain((expressionValue as ExpressionBool).GetExpression(), op);
             UsedWidgetIDs = CombineWidgets(expressionValue);
             return(this);
         }
     }
     throw new InvalidOperationException(UserMessages.ExceptionNoComparison(Type, expressionValue.Type, op));
 }
コード例 #40
0
 private int GetPrecedence(ExpressionOperator op)
 {
     switch (op)
     {
         case ExpressionOperator.NOT:
         case ExpressionOperator.NEG:
             return 1;
         case ExpressionOperator.MOD:
         case ExpressionOperator.MUL:
         case ExpressionOperator.DIV:
             return 2;
         case ExpressionOperator.ADD:
         case ExpressionOperator.SUB:
             return 3;
         case ExpressionOperator.GT:
         case ExpressionOperator.GE:
         case ExpressionOperator.LT:
         case ExpressionOperator.LE:
             return 4;
         case ExpressionOperator.EQ:
         case ExpressionOperator.NE:
             return 5;
         case ExpressionOperator.AND:
             return 6;
         case ExpressionOperator.OR:
             return 7;
         default:
             return 0;
     }
 }
コード例 #41
0
ファイル: ExpressionBool.cs プロジェクト: njtromp/endless-ql
        /// <summary>
        /// Combines two boolean expressions
        /// </summary>
        /// <param name="item1">Left hand side</param>
        /// <param name="item2">Right hand side</param>
        /// <param name="op">Operator</param>
        /// <returns>Resulting delegate</returns>
        protected override Func <bool> CombineExpressions(Func <bool> item1, Func <bool> item2, ExpressionOperator op)
        {
            switch (op)
            {
            case ExpressionOperator.And:
                return(() => item1() && item2());

            case ExpressionOperator.Or:
                return(() => item1() || item2());

            case ExpressionOperator.Equals:
                return(() => item1() == item2());
            }

            throw new InvalidOperationException(UserMessages.ExceptionNoCombination(Type, Type, op));
        }
コード例 #42
0
 protected internal ODataExpression(ODataExpression left, ODataExpression right, ExpressionOperator expressionOperator)
 {
     _left = left;
     _right = right;
     _operator = expressionOperator;
 }
コード例 #43
0
 Polynomial <TVar, TExpr> SwapOperands(ExpressionOperator newOp)
 {
     return(new Polynomial <TVar, TExpr> (newOp, right, left));
 }
コード例 #44
0
 public ExpressionData( string left, ExpressionOperator ope, object right )
     : this()
 {
     LeftOperand = left;
     Operator = ope;
     RightOperand = right;
 }
コード例 #45
0
 protected DynamicFilterExpression(FilterExpression left, FilterExpression right, ExpressionOperator expressionOperator)
     : base(left, right, expressionOperator)
 {
 }