build-a-programming-language / lesson-35.md
Lesson 35 · Functions & closures

Parsing function literals

Functions are values in this language, written with fn. Today you parse a function literal into a node holding its parameter names and body block - back to the parser for one lesson to give the evaluator something to run.

The goal

Parse a function literal into a node with its parameter list and body block.

Start here - the target
TO DO
Scenario: Parsing a function literal
Giventhe source fn(x, y) { x + y }
Whenthe parser parses the program and prints it
Thenthe printed form is fn(x, y) (x + y)
Andparsing fn() { } prints fn() with an empty parameter list and empty body
Background

A function literal starts with fn, a parenthesized list of parameter names, and a body block - and crucially it is an expression, a value you can bind to a name or pass around, not a named declaration. Register fn as a prefix parse function: parse the comma-separated identifiers between the parentheses, then reuse parseBlock for the body.

Parsing the parameter list is the one new bit - handle zero parameters (fn() { }), one, and several separated by commas. The body reuses machinery you already have. This is a brief detour back into the parser; the next lesson adds call syntax, and then the evaluator brings both to life.

Make it work
type FunctionLiteral struct { Parameters []*Identifier; Body *BlockStatement }
// register 'fn' as a prefix parse function:
// consume 'fn', parse a comma-separated parameter list in ( ),
// then parse the body with parseBlock
CheckpointDONE
Function literals parse into a node with parameters and a body. Commit.