Example #1
0
        /// <summary>
        /// The shunting yard algorithm that processes a postfix list of expressions/operators.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="parser"></param>
        /// <param name="stack"></param>
        /// <returns></returns>
        public static Expr ProcessShuntingYardList(Context context, Parser.Parser parser, List <object> stack)
        {
            int  index    = 0;
            Expr finalExp = null;

            // Shunting yard algorithm handles POSTFIX operations.
            while (index < stack.Count && stack.Count > 0)
            {
                // Keep moving forward to the first operator * - + / && that is found
                // This is a postfix algorithm so it works by creating an expression
                // from the last 2 items behind an operator.
                if (!(stack[index] is TokenData))
                {
                    index++;
                    continue;
                }

                // At this point... we hit an operator
                // So get the last 2 items on the stack ( they have to be expressions )
                // left  is 2 behind current position
                // right is 1 behind current position
                var       left  = stack[index - 2] as Expr;
                var       right = stack[index - 1] as Expr;
                TokenData tdata = stack[index] as TokenData;
                Token     top   = tdata.Token;
                Operator  op    = Operators.ToOp(top.Text);
                Expr      exp   = null;

                if (Operators.IsMath(op))
                {
                    exp = Exprs.Binary(left, op, right, tdata);
                }
                else if (Operators.IsConditional(op))
                {
                    exp = Exprs.Condition(left, op, right, tdata);
                }
                else if (Operators.IsCompare(op))
                {
                    exp = Exprs.Compare(left, op, right, tdata);
                }

                parser.SetupContext(exp, tdata);
                stack.RemoveRange(index - 2, 2);
                index        = index - 2;
                stack[index] = exp;
                index++;
            }
            finalExp = stack[0] as Expr;
            return(finalExp);
        }