Topic 3 · Class activity 1 · Week 6 · Wednesday

Precedence and Associativity Lab

Six expressions, six trees, then break the precedence table and explain each change by the shape of the tree.

Format pairsTime 40 minBring paper

The point

Precedence and associativity are two separate decisions that people routinely conflate. Separate them by hand, then confirm against the machine.

Do this

  1. Draw the syntax tree for each of these, using the precedence table from the notes. Do not run anything yet.
    2 + 3 * 4
    (2 + 3) * 4
    17 - 5 - 3
    -2 * 3
    2 * -3
    -8 / 2 / 2
  2. Evaluate each tree and write the number down.
  3. Check by compiling and running the three that differ most, then reconcile any disagreement.
  4. Change associativity. Make + and - %right. Predict which of your six expressions change value, then rebuild and check. Explain the result in terms of the shape of the tree.
  5. Remove %prec UMINUS from the unary-minus rule. Predict what happens to -8 / 2 / 2, then check. Which precedence does the rule inherit without it?
  6. Write the layered grammar for +, * and NUM — expr → term → factor — and say which form you would ship in a compiler other people maintain.

Deliverable

Six trees with their values, the results of experiments 4 and 5, and your layered grammar with a one-paragraph argument. Feeds Lab Question 3.