[antlr-interest] Expression Tree failed in some multiple signs case

Jason Yip jasonyipwa at yahoo.com
Fri Nov 29 03:43:44 PST 2002


Hi everybody, I was writing a program to covert an expression to an expression tree using stack. But when it comes to multiple signs, my program will fail.
     inputFormula1 = "(-4--12*(3++--30/2))";     inputFormula2 = "(3*2+1^2*(5-2--2*6))";     Assume that plus sign is #, minus sign is ~    In inputFormula1, we can rewrite the inner part as 3+#~~30/2, my code is while (!operatorStack.isEmpty()) {
 stackOperator = (OperatorToken) operatorStack.peek();
 if ( (stackOperator.priority() >= thisOperator.priority()) &&
  (stackOperator.getToken() != OperatorToken.LeftParen) ) {
   // output the operator to the return stack 
   operatorStack.pop();
   returnStack.push(stackOperator);
} else
 break;
     output 3            output 3            output 3#            output 3#~            operator +        operator +#      operator +~        operator +~            output 3#~30        output 3#~30~2        output 3#~30~2/+    operator +~          operator +/                operator     Notice the fourth column, output is 3#~, and the top is stack was being compared with another ~, since they have the same priority, the ~ in the stack is being pushed, and another ~ is being pushed to opeartor stack. When we read 30, it will be pushed to output, like column 5. It will result a ~#3 and a ~30. It is wrong!     So I changed the code to     if ( (stackOperator.priority() > thisOperator.priority())...     The result will be correct.     However, in inputFormula2, it will result 522~--6* instead of 52-2~-6*.     Well, what I was saying is the compare method will fail in some case with multiple signs. But it would work in some other case. What can I do to fix it? Jason 


---------------------------------
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20021129/35690045/attachment.html


More information about the antlr-interest mailing list