liveBook · Manning

Operator associativity

As explained in Building User-Friendly DSLs

A binary operator whose equal-precedence sequences are grouped from left to right.

A left-associative binary operator groups equal-precedence operations from left to right. Thus, 3 - 2 - 1 means (3 - 2) - 1, producing 0 rather than 3 - (2 - 1), which produces 2. section 12.3

The rule applies repeatedly: x1 op1 x2 op2 x3 op3 x4 becomes ((x1 op1 x2) op2 x3) op3 x4 when the operators share precedence and are left-associative. Expression ASTs therefore grow toward the left. section 12.3

Arithmetic chain

For 1 + 2 + 3 + 4, build the tree as (((1 + 2) + 3) + 4). Parentheses can override this grouping, as in 1 + (2 - 3). section 12.3

Figure 12.15 The AST representing the expression 3 – 2 – 1, taking the order of operations for the left-associative – operator into account
figure

Inspect the AST for 3 - 2 - 1 to see how left associativity determines its nested structure. section 12.3

How Building User-Friendly DSLs covers it

How deep it goes
Explains repeated grouping, AST consequences, and parentheses, while contrasting but not developing right-associative implementation.
Examples
Uses 3 - 2 - 1, chained addition, parenthesized subtraction, AST figures, and a requiresParentheses condition.
What it assumes
Assumes binary operations and precedence, then establishes associativity as an additional ordering rule.
What you can do after
Evaluate/understand equal-precedence expression chains and predict their nested AST structure.
How it connects
Connects binary operators with equal precedence, order of operations, abstract syntax trees, parentheses, and right-associative operators.

Related concepts

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.