More Ppml tools: Restoring parentheses

Although straightforward, our preliminary pretty printer tells us nothing about operator priorities or parenthesized expressions. Our pretty printer formats the expressions (12 + VAR1) * 24 and 12 + (VAR1 * 24) identically, even though the underlying abstract trees differ. A better version of basic will insert clarifying parentheses. No operator of the abstract syntax corresponds to parentheses, so we cannot use simple pattern matching methods to recognize the operator hierarchy. To introduce priority, we make use of several sophisticated Ppml features such as internal function definitions, the if control statement, the where statement, external functions calls, and contexts.

In both of the abstract syntax trees shown in figure , the expression in parentheses, which has the higher priority, appears farther down the tree. We know, therefore, that since the plus operator has a lower priority than the prod operator, when it appears farther down the tree it must be within parentheses. If we assign low integers to the operators with the highest priority (* = 2, +,- = 3, etc.), we can express our priority check as follows:

 
if {precedence(*left-child) > precedence (*current-op)}
   then put parentheses around *left-child
else
   no parentheses around *left-child

If the precedence of the right descendent is greater than or equal to the precedence of the current operator, we put parentheses around the right operator.

 
if {precedence(*right-child) > or = precedence (*current-op)}
   then put parentheses around *right-child
else
   no parentheses around *right-child

We treat the case of ``equal to'' since we want our expressions to be left associative.



Tutorial