Crafting Interpreters · Week 7

Ch 9: Control Flow

Updated

About 4 hoursVerified by tests

Summary

Crafting Interpreters chapter 9, Control Flow: if/else, logical operators with short-circuiting, while loops, and for loops implemented by desugaring into while. Budget about 4 hours; the book's chap09_control tests check your code.

Lox becomes Turing-complete.

Flashcards 6 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

This week's steps

4 steps
  1. Read the chapter

    After implementing for-loop desugaring, print the AST of a for loop to see the rewritten while loop.

  2. Write the code in your lox repo

    Type it into jlox/ (Java) yourself as you read, and get it running.

  3. Do the challenges (1–3)

    Challenge 3 (add break) is the one to implement; it is a good exercise in parser state and in using an exception or flag to unwind.

  4. Push and let the tests verify it

    Your repo runs the book's chap09_control tests on every push; passing marks this done.

Sign in to track this: tick each step off and it counts toward your week.

Try it in the browser

Optional

jlox as it stands at the end of chapter 9: what this chapter adds works, and anything from a later chapter is the error your own jlox would give. Compare its output with yours. The full playground

Chapter 9: Control Flow

Everything up to chapter 9, Control Flow. Later features are syntax errors here.

Output
Run the code to see what it prints.

jlox from Crafting Interpreters by Robert Nystrom, ported to TypeScript (MIT).

Your notes

Only you

Sign in to keep private notes on this guide, in Markdown. They stay yours: never on your profile, and you can export them all.

Discussion

0 posts

Questions about this chapter, tips, and what tripped you up. Hints over answers: full solutions go in a spoiler.

No posts yet. Ask a question or share a tip.

Sign in to postAnyone can read. Posting needs an account with a confirmed email.

Reference

Why it matters

Desugaring (implementing a feature by rewriting it into simpler features) is a key compiler technique. Short-circuit evaluation shows up in every language.

How to approach it

After implementing for-loop desugaring, print the AST of a for loop to see the rewritten while loop.

Challenges

3 challenges at the end of the chapter.

Challenge 3 (add break) is the one to implement; it is a good exercise in parser state and in using an exception or flag to unwind. Challenges 1 and 2 are thought exercises. Do challenges that change Lox's behavior on a separate git branch. The cracked.guide check runs the official test suite for this chapter, and a challenge that changes semantics (new syntax, different errors) can make tests fail on main.

Common traps
  • The dangling else: make sure else binds to the nearest if.
  • Logical operators must return the operand value, not a converted boolean.

Spot a mistake? Report it

Back to week 7