What building an interpreter teaches about type design
// status: seedling
An interpreter is a small compiler with the lights on. It has a front end that turns text into structure, a middle that gives the structure meaning, and a runtime that has to make choices about names, values, errors, and control flow. That makes it a particularly good place to learn type design: every vague boundary becomes a bug you can observe immediately.
I felt this while making Monkey language interpreter made in Rust. The project started from Writing an Interpreter in Go, but the Rust version uses Nom for lexing/parsing and builds an AST before evaluation. The language is dynamically typed; the implementation does not have to be. Rust's enums, Result, ownership rules, and exhaustiveness checks became a set of guard rails around a deliberately dynamic language.
The lesson is not “put a type around everything.” It is: make each phase's vocabulary explicit, and make invalid transitions difficult to express.
Draw the phases before writing the types
A useful first sketch is:
source text
│
▼
tokens + source spans
│
▼
AST (syntax, still unexecuted)
│
▼
runtime evaluation with an environment
│
▼
value or runtime errorEach arrow is a boundary. A lexer should not return an evaluated integer. An AST should not contain a mutable environment. A runtime Value should not be mistaken for a source-level IntegerLiteral. The names may look similar, but their invariants are different.
I now try to answer these questions before choosing a representation:
- What information is needed to report an error at the source location?
- Which variants are valid in this phase but impossible in the next?
- Is this data syntax, a runtime value, or an instruction to perform an action?
- Who owns the data, and can two parts of the interpreter mutate it at the same time?
- Is failure expected and recoverable, or is it an invariant violation?
The answers usually point to a separate type rather than another flag on a large struct.
Tokens are not strings with opinions
A token boundary is the first chance to retain useful information. A token kind says what the lexer saw; a span says where it saw it; the source text remains the original evidence.
The exact token inventory in Monkey can grow, but the separation is stable. TokenKind::Int says “the parser may interpret this as an integer literal”; lexeme preserves the source spelling for diagnostics; Span prevents every error message from becoming “somewhere in the file.” A parser that accepts a raw String everywhere loses these distinctions and then has to reconstruct them later.
In a production parser I would likely use a borrowed slice or an interned symbol rather than allocating a String for every token. That is an optimisation choice, not a reason to collapse token identity and token text into one untyped value.
The AST should describe syntax, not execution
The AST is where precedence, nesting, and source-level intent become explicit. A compact Monkey-shaped version might look like this:
This is intentionally syntax-shaped. Expr::Int(2) means that the source contained an integer literal; it does not mean that the runtime has already allocated a Value::Int(2). Keeping the two types separate makes the evaluator's job visible instead of making it an accidental cast.
There is a useful asymmetry here. An AST may contain an identifier that has not been defined, a call whose callee is not callable, or a condition that is not boolean. That is fine if Monkey is dynamically typed. The AST represents what the parser accepted; the evaluator reports what the runtime rejects.
If the language later gains a static type checker, add a phase and a type representation rather than mutating Expr into a half-evaluated object:
The same syntax can then be checked, annotated, compiled, or interpreted by separate consumers.
Runtime values are a different algebra
The evaluator needs a closed set of values that can exist while a program runs. It is not the same set as the AST variants.
use RefCell;
use HashMap;
use Rc;
type Env = ;
The Function value captures an environment. Rc<RefCell<_>> is a pragmatic representation for a small interpreter: multiple closures can share an environment, and mutation is checked at runtime by RefCell. It is not a claim that all interpreters should use reference counting or interior mutability. It is a type-level acknowledgement that lexical closures introduce shared ownership and potentially dynamic borrow conflicts.
If the language supports hashes, a separate HashKey is worth introducing rather than assuming every Value can be a map key:
// The runtime can then use HashMap<HashKey, Value> and reject arrays,
// functions, and null as keys at the language boundary.That restriction is a domain rule. Giving it a name means it can be tested independently and reported without a panic from the host HashMap.
Errors should retain the phase that produced them
Parsing and evaluation fail for different reasons. A parser error means the source did not form a valid program; an evaluation error means a valid-looking program encountered a bad runtime operation.
The public phase functions can now say what they do:
In actual code I would use a real Program type and return source spans in EvalError as well. The important part is that Result marks expected failure as data. A parser can collect several errors; an evaluator can stop at the first runtime error or add a language-level error value. Neither should need to panic for ordinary user mistakes.
Pattern matching makes language growth honest
The evaluator naturally follows the AST algebra:
The helper functions are omitted here to keep the boundary in focus. The match is still valuable: adding While, Index, or MacroCall forces every consumer to make an explicit decision. Rust's exhaustiveness checker turns language evolution into a to-do list.
That is one place where the implementation language shapes the experience. OCaml variants have the same algebraic clarity, but exhaustiveness is normally a warning unless the build promotes it. Haskell's algebraic data types offer the same pattern-matching model, with warnings depending on compiler flags. In all three languages, a deliberate warning policy matters more than the spelling of the enum.
Type the control-flow stories, too
Monkey's return is not an ordinary value-level fallthrough. A simple evaluator can model it as a special runtime value and unwrap it at block boundaries; a more explicit design gives control flow its own type:
This separates “the expression evaluated to a value” from “the function asked to return.” It prevents a nested block evaluator from accidentally swallowing a return or treating it as a normal value. An implementation may choose an internal exception, a tagged value, or a continuation; the type makes the desired boundary reviewable.
The same thought applies to closures. A closure is not merely a function plus a list of parameter strings; it is a function body paired with the environment visible at definition time. Naming that pair in Value::Function made the closure semantics in the Rust project much easier to reason about than a pile of loosely related fields.
What the host type system can and cannot prove
Rust can prove properties of the interpreter implementation: a Token has a valid Span shape, a Result is handled or explicitly ignored, and a borrowed AST cannot outlive the source it references if the types are designed that way. It cannot prove that a Monkey Value::Int is the result of a well-typed Monkey program unless we build a Monkey type checker.
This distinction prevents overclaiming. The host type system protects the meta-language; the interpreter's own type rules protect the interpreted language. A dynamically typed Monkey program may still fail with TypeMismatch, and that is a feature of the language semantics, not a failure of Rust's type system.
If we eventually add static typing to Monkey, the pipeline becomes:
tokens → untyped AST → typed AST → runtime/compilerA typed AST can encode facts such as “this condition is boolean” or “this expression returns an integer,” but it also introduces type inference, error recovery, and a decision about where annotations live. The small interpreter is a good place to learn those trade-offs because the untyped baseline remains available for comparison.
A design workflow I would reuse
- Write the phase diagram. Name the data crossing each arrow.
- Give domain concepts newtypes.
Identifier,Span,HashKey, andTokenprevent accidental interchange. - Use enums for closed alternatives. Let the compiler enumerate the work when the language grows.
- Separate syntax from meaning. Keep
ExprandValuedistinct even when their cases look similar. - Make expected failures data. Use
Resultwith errors that preserve phase and location. - Model non-local control explicitly.
return,break,continue, and suspension should not hide inside ordinary values by accident. - Test each boundary. Lexer tests should not need an evaluator; evaluator tests should be able to construct ASTs directly.
The payoff is not only fewer crashes. It is a program whose architecture explains the language: the parser owns syntax, the evaluator owns runtime meaning, the environment owns bindings, and errors say which boundary rejected the input.
Things that tripped me up
- Confusing an AST literal with a runtime value.
Expr::Int(2)is syntax;Value::Int(2)is the result of evaluation. Reusing one type makes phase boundaries disappear. - Treating every failure as a string. A message such as “expected right paren” is useful to a person but not to a test or editor. Keep a structured error and render it at the edge.
- Using
Optionfor errors.Noneloses the reason parsing or lookup failed. UseResultwhen the caller can act on the failure. - Forgetting closure environments. A function body plus parameters is not a closure. The defining environment is part of the runtime value.
- Letting
returnfall through. A return is a control-flow signal, not just anotherValue; block evaluators need a typed way to propagate it. - Assuming dynamic language means untyped implementation. Rust can enforce the interpreter's phase invariants while Monkey remains dynamically typed.
- Making host containers define language rules by accident. Hashability, arity, truthiness, and equality belong in named helpers or types, not in whatever behaviour a standard-library container happens to expose.
- Optimising ownership before understanding semantics.
Rc<RefCell<_>>is not the final word on environments; it is a transparent first model for sharing and mutation. Optimise after closure and scope tests pass.
References
- Monkey language interpreter made in Rust
- Monkey language interpreter made in Rust
- The Rust Programming Language — Enums and pattern matching
- The Rust Programming Language — Error handling
- Rust core documentation —
Result - Rust Reference — Generic parameters and bounds
- Writing an Interpreter in Go — Monkey language
- Nom parser combinator library
- OCaml manual — Generalized algebraic datatypes
Back to Notes · see also OCaml - learning log · GADTs Through a Small Typed Expression Evaluator · Home.