liveBook · Manning

Parenthesis

As explained in Building User-Friendly DSLs

A paired expression delimiter that explicitly groups an expression and can alter its structural interpretation.

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)
figure

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

How Building User-Friendly DSLs covers it

How deep it goes
Explains recursive evaluation, Parentheses AST objects, AST construction, and equal-precedence projection criteria.
Examples
Uses 1 + 2 * (3 + 4), 1 + (2 – 3), and exponentiation expressions to demonstrate grouping.
What it assumes
Assumes familiarity with arithmetic operators while defining recursive subexpression evaluation and order of operations.
What you can do after
Build it from scratch by representing parenthesized subexpressions in ASTs and emitting parentheses when associativity requires them.
How it connects
Connects parentheses with order of operations, expression ASTs, operator precedence, associativity, and binary operations.

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.