Exercise 2: Compiling a Desugared For-Loop — Possible Solution ==================================================================== THE DESUGARED TREE ------------------------------ for (var i = 0; i < 3; i = i + 1) { print i; } desugars (per Course 1, Chapter 6's own parser-level rule) to: BlockStmt([ VarStmt('i', Literal(0.0)), WhileStmt( Binary(Variable('i'), '<', Literal(3.0)), BlockStmt([ BlockStmt([PrintStmt(Variable('i'))]), # the for-loop's own body ExpressionStmt(Assign('i', Binary(Variable('i'), '+', Literal(1.0)))), # increment ]), ), ]) RESULT ------------------------------ ['0', '1', '2'] WHICH VISIT_* METHODS HANDLE IT ------------------------------ BlockStmt (outer, holds the var + while) -> visit_block_stmt VarStmt('i', ...) -> visit_var_stmt WhileStmt(...) -> visit_while_stmt Binary('<', ...) -> visit_binary Variable('i') -> visit_variable Literal(...) -> visit_literal BlockStmt (inner, holds the loop body) -> visit_block_stmt (again -- same method) PrintStmt(...) -> visit_print_stmt ExpressionStmt(Assign(...)) -> visit_expression_stmt, then visit_assign Every single one of these already existed before this chapter's own for-loop exercise was written -- visit_block_stmt, visit_var_stmt, and visit_while_stmt come from this chapter and Chapter 4; visit_binary, visit_variable, and visit_literal come from Chapter 3; visit_print_stmt, visit_expression_stmt, and visit_assign come from Chapter 4. WHY THIS WORKS AS AN ANSWER ------------------------------ No new AST node type (a hypothetical ForStmt) and no new visit_for_stmt method exist anywhere in this compiler, and the program still compiles and runs correctly. This is only possible because the DESUGARING happened one stage earlier, in Course 1's own parser -- by the time this compiler ever sees the tree, "for" has already been rewritten into a var declaration wrapping a while loop, using node types the compiler already knew how to handle from Chapters 3 and 4. The compiler doesn't need to know "for" exists as a concept at all. This is the exact same payoff Course 1, Chapter 6 found for its own tree-walking interpreter ("zero new interpreter methods") showing up again here, one course and one completely different execution strategy later, for the identical underlying reason: the work of supporting `for` was done once, at the parser, and every consumer of the AST downstream -- a tree-walker, or now a bytecode compiler -- gets it for free.