liveBook · Manning

Virtual parentheses

As explained in Building User-Friendly DSLs

Projection-only parentheses displayed to clarify an expression's AST grouping without being represented in the underlying expression AST.

Virtual parentheses are projection-only parentheses added when an expression AST’s grouping would otherwise be displayed ambiguously. They clarify operator-precedence grouping without changing the underlying expression AST. section 12.2 section 12.5

Implement virtual parentheses by:

  • Defining operator precedence and comparing a nested binary operation with its parent. section 12.2
  • Wrapping the nested operation when the parent operator has lower precedence. section 12.2 section 12.5
  • Applying the same criterion to the UI projection and generated code, while leaving the AST unchanged. section 12.2

Disambiguating 1 * (2 + 3)

An AST for 1 * (2 + 3) can otherwise project like 1 * 2 + 3. Virtual parentheses make the grouping visible in the projection and preserve equivalent grouping in generated code. section 12.2 section 12.5

Figure 12.14 The criterion to decide whether a binary operation needs to be wrapped in parentheses because of order of operations in combination with operator precedence
figure

Use the precedence criterion to determine when a nested binary operation needs projection-only parentheses. section 12.2

How Building User-Friendly DSLs covers it

How deep it goes
Defines the precedence criterion and implements it in both projection and code generation, without modifying the expression AST.
Examples
Uses 1 * 2 + 3 and 1 * (2 + 3) to expose identical projections and correct their displayed grouping.
What it assumes
Assumes expression ASTs, nested binary operations, and operator precedence while teaching the wrapping criterion explicitly.
What you can do after
Build it from scratch by calculating precedence and conditionally rendering parentheses in projections and generated expressions.
How it connects
Connects abstract syntax trees, operator precedence, binary operations, projections, and code generation.

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.