Exemplo n.º 1
0
        protected void pushOperator(Lexeme op)
        {
            if (!op.IsOperator())
            {
                throw new ParseException("Cannot push a non-operator token onto the operator stack!");
            }

            if (op.IsRightAssociative())
            {
                // pushing a right-associative operator
                // pop the top of the stack into the output queue as long as it isn't
                // an opening parenthesis or its precedence is lower or equal to that of
                // the operator being pushed onto the stack
                try
                {
                    while (true)
                    {
                        Lexeme stackTop = operatorStack.Peek();
                        if (stackTop.Type == Lexeme.LexemeType.LEFT_PAREN)
                        {
                            break;
                        }
                        else if (stackTop.IsHigherPrecedenceThan(op))
                        {
                            output.Enqueue(stackTop);
                            operatorStack.Pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                catch (InvalidOperationException ex)
                {
                    // operator stack is empty, continue with pushing operator
                }

                lastProcessedElement = op;
                operatorStack.Push(op);
            }
            else
            {
                // pushing a left-associative operator
                // pop the top of the stack into the output queue as long as it isn't
                // an opening parenthesis or its precedence is lower to that of
                // the operator being pushed onto the stack
                try
                {
                    while (true)
                    {
                        Lexeme stackTop = operatorStack.Peek();
                        if (stackTop.Type == Lexeme.LexemeType.LEFT_PAREN)
                        {
                            break;
                        }
                        else if (!stackTop.IsLowerPrecedenceThan(op))
                        {
                            output.Enqueue(stackTop);
                            operatorStack.Pop();
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                catch (InvalidOperationException ex)
                {
                    // operator stack is empty, continue with pushing operator
                }

                lastProcessedElement = op;
                operatorStack.Push(op);
            }
        }