Parentheses are paired delimiters that make a subexpression explicit. During arithmetic evaluation, a matched pair and its contents are evaluated first; the whole parenthesized expression is then replaced by its numeric result. This recursive step overrides the order that unparenthesized operators would otherwise impose. section 12.1
In an expression AST, parentheses preserve intended grouping rather than merely decorate printed code. A Parentheses AST object wraps the inner expression, allowing the AST for 1 + 2 * (3 + 4) to retain that 3 + 4 must be completed before multiplication. section 12.1
Parentheses serve two closely related jobs:
- Force a nested subexpression to be evaluated before surrounding operations, such as evaluating (3 + 4) before multiplying it by 2. section 12.1
- Preserve an AST whose grouping conflicts with the default precedence or associativity of its printed operators. section 12.3
- Wrap a right operand when it is a binary operation of equal precedence and omitting the wrapper would change a left-associative interpretation. section 12.3
Making an intended tree printable
The AST grouping 1 + (2 – 3) cannot be projected safely as 1 + 2 – 3: addition and subtraction are left-associative, so the unparenthesized form groups differently. Wrapping 2 – 3 preserves the intended right operand. The same concern applies when projecting expressions with equal-precedence operators. section 12.3
Figure 12.8 Building an AST for the expression 1 + 2 * (3 + 4)
Inspect the AST built for 1 + 2 * (3 + 4) to see parentheses represented as an explicit nested expression rather than inferred from operator precedence alone. section 12.1
