Friday, March 19, 2010

Translator – Operator Precedence

The precedence member needs to be added to the Table, which the Translator will use to rearrange the input to the output RPN list. After considering the operator precedence in several BASICs and in C, the operator precedence that will be used for this project is (from highest to lowest):
^             (exponentiation)
-             (negation)
*, /          (multiplication, division)
\             (integer division)
MOD           (modulus)
+, -          (addition, subtraction)
<, >, <=, >=  (relational operators)
=, <>         (equivalence operators)
NOT           (logical not/1's compliment)
AND           (logical/bit wise and)
XOR           (logical/bit wise exclusive or)
OR            (logical/bit wise or)
IMP           (implication)
EQV           (equivalence)
Previously mentioned in post Translator – Unary Operators that the unary operators would be a high precedence. This is the case in C, however this is not the case in the BASICs. The exponentiation operator is higher precedence (an operator that C does not have). Consider the example -X2 where algebraically X would be squared first then the result negated. More ambiguous is when constants are involved, consider the example -52 where the result would be -25. The ambiguity occurs because -5 is a legal constant, so, should -5 be squared first resulting in 25? However, the Parser currently does not attach signs to constants (minus signs are parsed as operators). The plan was to roll negation back into a constant, but considering higher precedence of exponentiation, this will not be done. GW-Basic does give -25 for -5^2 (though strangely SmallBASIC does negation before exponentiation).

All BASICs set the precedence of the relation and equivalence operators at the same level, however, C has them separate. Consider the example A < 4 = B > 2, which using the precedence above would be evaluated as (A < 4) = (B > 2), which make sense and probably explains C's precedence. The BASICs would instead evaluate that as less logical ((A < 4) = B) > 2. Therefore the C precedence was chosen. (Remember something unique is being created here and there is not a big concern about compatibility.)

As for the logical operators, the BASIC seem to have the precedence order of NOT, AND, and OR; but ordering of the rest is inconsistent. Again, the C precedence placement of XOR was chosen, though NOT was placed at the top of the logical operators, but below that other operators. Consider the example NOT A = B, which would be evaluated at NOT (A = B), in other words, A <> B; instead of the less logical (NOT A) = B.  The EQV and IMP was placed lowest with EQV at the bottom for the same reason as placing the equivalence operators below the relational operators.

No comments:

Post a Comment

All comments and feedback welcomed, whether positive or negative.
(Anonymous comments are allowed, but comments with URL links or unrelated comments will be removed.)