docs

#A small Lisp interpreter

On this page

Build a small Lisp with a tokenizer, a recursive-descent parser and an evaluator that carries an environment, supporting define, if, lambda and closures, with runtime errors reported through throws.

#Code

#Walkthrough

  • Programs and values share one enum, Value. Because Lisp code and data have the same shape, the parser produces Values and the evaluator takes a Value and returns a Value (Sum types, Structs, enums and traits).
  • The parser shares its read position with the caller through ref pos: usize. It is a classic recursive-descent parser that calls itself to read inside parentheses (4.7 the ref keyword).
  • Any token that isn't an integer is a symbol. try? tok.parse::<i64>() turns the parse error into none, so a two-armed match separates the cases (3.14.3 try? and try!). Where only one variant is acceptable, a let-else such as let Value::Sym(name) = items[1] else { throw ...; }; binds it or leaves the function.
  • Runtime errors throw a LispError, and each function states this in its signature with throws (LispError). The try { ... } catch e: LispError { ... } at the bottom turns one line's error into a message, so the next line still runs (Errors).
  • A lambda captures the Env it was created in. Dict is a shared reference, so the function returned by make-adder remembers k, and fact can find itself even though it is defined afterwards.

Note

An enum that contains itself directly (Lambda(..., Value, ...)) would have infinite size, so the compiler rejects it; lambda bodies are kept in a List<Value> instead.

Found a mistake? Edit this page on GitHub. Last updated