Wednesday, November 6, 2013

Recreator – Parentheses (Unary Operators)

Handling the recreation of parentheses with unary operators is similar to that of binary operators except there is only one operand with another issue.  As with binary operators, if the precedence of the unary operator is higher than the operand on top of the stack, parentheses should be added around the operand.  However, parentheses should only be added if the operand on top of the holding stack is not another unary operator.  Consider the expression and its translation:
-NOT A%            A% NOT Neg%
When the Neg% operator is being processed, its precedence is higher than the NOT on top of the stack (actually the top contains the string "NOT A%" with the precedence of the NOT operator).  With just the precedence check, parentheses would be added around the "NOT A%" expression, which is not correct.  There needs to be an additional check to not add parentheses if the top item is a unary operator expression.

Implementation

A unary operator flag variable was added to the stack item to indicate if the holding stack item is a unary operator sub-expression.  The push access function was modified to take an optional unary operator flag value that is pushed with the string and precedence.  The default flag is set to false and is only set to true by the unary operator recreate function.

The unary operator recreate function was modified to get the precedence of the operator being processed from the table.  The pop call of the operand was changed to call the new pop with parentheses with the argument set to whether the top stack item is not a unary operator and the operator precedence is higher than the precedence of the top stack item.

There were insufficient expressions in expression test #2 (parenthetical expressions) to test the various situations with unary operators, so several were added.  The translated test expected results were also updated for the new expressions.  The expressions that still do not match are due to unnecessary entered parentheses.

[commit a5951ecfc3]