liveBook · Manning

Operator precedence

As explained in Building User-Friendly DSLs

The precedence rules that determine the sequence in which multiple operations are evaluated.

Operator precedence, also called operator priority, orders operators so an expression has a predictable evaluation order. Operations with higher-precedence operators are evaluated before lower-precedence ones; parentheses make a contained subexpression evaluate first. section 12.1 section 12.5

Reading arithmetic expressions

In 1 + 2 * 3, multiplication is evaluated before addition. In 1 + 2 * (3 + 4), the parenthesized addition is evaluated first, then multiplication, then the outer addition. Each completed subexpression is replaced by its result as evaluation proceeds recursively. section 12.1

Precedence must shape an expression AST, not merely its displayed symbols. An AST that groups the multiplication beneath the addition represents 1 + 2 * 3 correctly and supports code generation that preserves its intended runtime meaning. This also lets a projectional editor behave like familiar linear expression editing. section 12.0 section 12.5

When adjacent binary operators have unequal precedence, the higher-precedence operation groups first. Equal precedence needs associativity: left-associative operators group the left operation first, while right-associative operators group the right operation first. Projection can add virtual show-only parentheses when an AST’s displayed grouping would otherwise be ambiguous. section 12.5

Rental-price computation

A rental price after discount can be generated as rentalPriceBeforeDiscount - discount * 0.01 * rentalPriceBeforeDiscount. Multiplication groups before subtraction, producing the discount amount before subtracting it from the original price. section 11.3 section 13.1

Figure 12.5 Building an AST for the expression 1 + 2 * 3
figure

Trace how precedence determines the AST built for 1 + 2 * 3. section 12.1

How Building User-Friendly DSLs covers it

How deep it goes
Defines recursive evaluation, precedence, parentheses, and associativity, then applies them to AST construction and ambiguous projections.
Examples
Uses PEMDAS evaluations for 1 + 2 * 3 and 1 + 2 * (3 + 4), plus a rental-price calculation.
What it assumes
Builds from familiar arithmetic expressions and PEMDAS while introducing AST-based expression representation.
What you can do after
Evaluate/understand how operator ordering and associativity determine expression grouping, AST shape, and generated behavior.
How it connects
Connects expression ASTs, parentheses, associativity, projectional editing, code generation, and type systems.

Also explained in

Compare how 7 books explain operator precedence →

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.