Crafting Interpreters · Week 3

Crafting Interpreters 5: Representing Code: reading guide

Read the chapter

You design the syntax tree for expressions: context-free grammars, the expression grammar for Lox, a small Java program that generates the AST classes, and the Visitor pattern for operating on trees, ending with an AST pretty printer.

Time About 4 hours this week

Why it matters

ASTs are the central data structure of every compiler, linter and code formatter. The Visitor pattern explanation here is one of the clearest anywhere.

How to approach it

Write the GenerateAst tool exactly as shown; it saves a lot of typing later. Spend real time on the section about the expression problem and the Visitor pattern until you can explain why it exists.

Challenges

3 challenges at the end of the chapter.

Challenge 3 (an RPN printer) is short and a nice check that you understand visitors. Challenges 1 and 2 are thought exercises about grammars and functional versus object-oriented style.

Traps

  • Forgetting to rerun GenerateAst after changing the grammar, then wondering why classes are missing.
  • In other languages, a sum type plus pattern matching (Rust enums, TypeScript unions) can replace the Visitor pattern. That is fine, but understand what the Visitor is doing first.

Links

Back to week 3