Crafting Interpreters · Week 14

Ch 16: Scanning on Demand

Updated

About 4 hours

Summary

Crafting Interpreters chapter 16, Scanning on Demand: A new scanner for clox that produces tokens on demand instead of all at once, pointing into the source string rather than copying lexemes, with a hand-written trie-like switch for keywords. Budget about 4 hours; it is a reading chapter, with no tests to pass.

Flashcards 7 cards for Anki and AnkiMobile · all decks

Anki deck.tsv

Step through at your own pace; the arrow keys work too.

Crafting Interpreters · Ch 4 Scanning: characters into tokens Watch start and current walk the source, the lexeme grow, and each token appear the moment its lexeme ends.

start 6current 8lexeme >=

Tokens

  1. IFif
  2. LEFT_PAREN(
  3. IDENTIFIERn
  4. GREATER_EQUAL>=

The next character is '=', so match() consumes it: one GREATER_EQUAL token, not two.

This week's steps

3 steps
  1. Read the chapter

    Compare each function with your jlox scanner.

  2. Write the code in your lox repo

    Type it into clox/ (C) yourself as you read, and get it running.

  3. Do the challenges (1–3)

    Challenge 1 (string interpolation) is a great design problem; think through how the scanner would need to cooperate with the parser.

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

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

Zero-copy scanning is how fast real-world parsers work. The keyword switch is a neat trick worth stealing.

How to approach it

Compare each function with your jlox scanner. Note how lexemes are pointers plus lengths, not strings.

Challenges

3 challenges at the end of the chapter.

Challenge 1 (string interpolation) is a great design problem; think through how the scanner would need to cooperate with the parser. Challenges 2 and 3 are design discussions.

Common traps
  • Token lexemes are not null-terminated. Never pass them to printf with %s; use %.*s.
  • The source buffer must outlive all tokens.

Spot a mistake? Report it

Back to week 14