Lexing and Parsing: From Text to a Syntax Tree · seed 1 · A4, ink-friendly. The answer key prints on its own page for grown-ups.

From Letters to Trees

Computing · Computer Systems · ages 21-22
Name ______________________   Date ____________
  1. In total = price + 2 * count, what kind of token is 2?

    • A number
    • A name
    • An operator
  2. What is the lexer's job?

    • To run the finished program
    • To group characters into named tokens
    • To arrange tokens into a tree
  3. In a + b * c, the parser groups b * c before applying the plus.

    Circle one:   True   False

  4. In the tree for price + 2 * count, what sits directly under the plus?

    • price, 2, and count as three equal children
    • price on one side and the 2 * count subtree on the other
    • The 2 * count subtree alone
  5. How does the lexer split total = price + 2 * count?

    • Into one token per character
    • Into two tokens: left side and right side
    • Into seven tokens: name, equals, name, plus, number, star, name
  6. How does a - b - c group?

    • As a - (b - c)
    • It cannot be grouped at all
    • As (a - b) - c
  7. Which grammar rule makes minus left associative?

    • expr = expr - term | term
    • expr = term - expr | term
    • expr = term + term | term
  8. A student evaluates a - b - c as a - (b - c) and gets a wrong answer. What is the real mistake?

    • The tree used right grouping, but minus needs left grouping
    • Arithmetic works differently inside compilers
    • Token lists cannot hold minus signs
LightMySky · lightmysky.comW1-mt_-ZlCxZ3SOh-s1

Answer key

For grown-ups. Fold this page away before handing over the rest.

From Letters to Trees W1-mt_-ZlCxZ3SOh-s1

  1. A number · Digits form numbers, letters form names, and symbols like plus form operators.
  2. To group characters into named tokens · Grouping characters is the lexer's whole task. The tree belongs to the parser.
  3. True · The star binds tighter, so its subtree forms first.
  4. price on one side and the 2 * count subtree on the other · Plus joins two parts: price and the already-built 2 * count subtree.
  5. Into seven tokens: name, equals, name, plus, number, star, name · The lexer reports every piece with its kind. Count them: seven.
  6. As (a - b) - c · Minus is left associative, so grouping starts from the left.
  7. expr = expr - term | term · Recursion on the left grows the tree to the left. That shape is left associativity.
  8. The tree used right grouping, but minus needs left grouping · The tokens were fine and arithmetic is normal. The tree shape was wrong, so the rule needs fixing.
Worksheet · LightMySky