Stack<OperatorNode> incompleteExprStack = new Stack<OperatorNode>(); // incomplete
// expression stack
Stack<ExpressionNode> wellFormedExprStack = new Stack<ExpressionNode>(); // well-formed
// expression
// stack
OperatorNode op1 = null;
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.trim().length() == 0) {
// ??
} else if (token.equals("(")) { //$NON-NLS-1$
++leftParenthesis;
ExpressionNode node = doParse(tokenizer.getUnparsedPartOfExpression());
wellFormedExprStack.push(node);
while (!incompleteExprStack.empty()) {
OperatorNode op = incompleteExprStack.pop();
if (wellFormedExprStack.empty()) {
throw new IllegalStateException("Invalid expression: " + expr + //$NON-NLS-1$
"\nThe operator '" + op.toString() + "' is missing an argument."); //$NON-NLS-1$ //$NON-NLS-2$
}
op.addOperand(wellFormedExprStack.pop());
// op.swapOperands();
wellFormedExprStack.push(op);
}
continue;
} else if (token.equals(")")) { //$NON-NLS-1$
++rightParenthesis;
break;
} else if ((op1 = opTokenToOp.get(token)) != null) {
onNewOperator(op1.makeOperator(), incompleteExprStack, wellFormedExprStack);
} else {
wellFormedExprStack.push(new LeafNode(operandFactory.getOperand(token), operations, operandFactory));
}
}
// The expression has been parsed.
// There maybe be zero or one binary and zero or more
// unary expressions on the incompleteExprStack.
while (!incompleteExprStack.empty()) {
OperatorNode op = incompleteExprStack.pop();
if (wellFormedExprStack.empty()) {
throw new IllegalStateException("Invalid expression: " + expr + //$NON-NLS-1$
"\nThe operator '" + op.toString() + "' is missing an argument."); //$NON-NLS-1$ //$NON-NLS-2$
}
op.addOperand(wellFormedExprStack.pop());
// op.swapOperands();
wellFormedExprStack.push(op);
}
// In the end we should be left with a single well formed expression