Crafting Interpreters · Week 14
Ch 16: Scanning on Demand
Updated
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.
See it
All visualsStep through at your own pace; the arrow keys work too.
Tokens
- IF
if - LEFT_PAREN
( - IDENTIFIER
n - GREATER_EQUAL
>=
The next character is '=', so match() consumes it: one GREATER_EQUAL token, not two.
This week's steps
3 stepsCompare each function with your jlox scanner.
Write the code in your lox repo
Type it into clox/ (C) yourself as you read, and get it running.
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 youSign 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 postsQuestions 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.