./jerome{m}

~/Notes/What Building an Interpreter Teaches About Type Design.md · note · seedling · 8 min · updated

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:

text
source text
    │
    ▼
tokens + source spans
    │
    ▼
AST (syntax, still unexecuted)
    │
    ▼
runtime evaluation with an environment
    │
    ▼
value or runtime error

Each 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.

rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Span {
    start: usize,
    end: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum TokenKind {
    Let,
    Function,
    If,
    Else,
    Ident,
    Int,
    String,
    Plus,
    Minus,
    Slash,
    Star,
    Equal,
    EqualEqual,
    LParen,
    RParen,
    Illegal,
    Eof,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Token {
    kind: TokenKind,
    lexeme: String,
    span: Span,
}

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:

rust
#[derive(Debug, Clone)]
struct Identifier {
    name: String,
    span: Span,
}

#[derive(Debug, Clone, Copy)]
enum PrefixOp {
    Negate,
    Not,
}

#[derive(Debug, Clone, Copy)]
enum InfixOp {
    Add,
    Subtract,
    Multiply,
    Divide,
    Equal,
    NotEqual,
    LessThan,
    GreaterThan,
}

#[derive(Debug, Clone)]
struct Program {
    statements: Vec<Statement>,
}

#[derive(Debug, Clone)]
struct Block {
    statements: Vec<Statement>,
    span: Span,
}

#[derive(Debug, Clone)]
enum Statement {
    Let {
        name: Identifier,
        value: Expr,
    },
    Return(Expr),
    Expr(Expr),
}

#[derive(Debug, Clone)]
enum Expr {
    Ident(Identifier),
    Int(i64),
    Bool(bool),
    String(String),
    Array(Vec<Expr>),
    Prefix {
        op: PrefixOp,
        rhs: Box<Expr>,
    },
    Infix {
        lhs: Box<Expr>,
        op: InfixOp,
        rhs: Box<Expr>,
    },
    If {
        condition: Box<Expr>,
        consequence: Block,
        alternative: Option<Block>,
    },
    Function {
        params: Vec<Identifier>,
        body: Block,
    },
    Call {
        function: Box<Expr>,
        args: Vec<Expr>,
    },
}

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:

rust
#[derive(Debug, Clone, PartialEq, Eq)]
enum Type {
    Int,
    Bool,
    String,
    Null,
    Array(Box<Type>),
    Function { params: Vec<Type>, ret: Box<Type> },
}

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.

rust
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

type Env = Rc<RefCell<HashMap<String, Value>>>;

#[derive(Clone)]
enum Value {
    Int(i64),
    Bool(bool),
    String(String),
    Array(Vec<Value>),
    Function {
        params: Vec<Identifier>,
        body: Block,
        env: Env,
    },
    Null,
}

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:

rust
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum HashKey {
    Int(i64),
    Bool(bool),
    String(String),
}

// 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.

rust
#[derive(Debug, PartialEq, Eq)]
enum ParseError {
    UnexpectedToken { expected: TokenKind, found: TokenKind, span: Span },
    InvalidInteger { lexeme: String, span: Span },
    UnexpectedEof { span: Span },
}

#[derive(Debug, PartialEq, Eq)]
enum EvalError {
    UnknownIdentifier { name: String },
    TypeMismatch { expected: &'static str, found: &'static str },
    UnknownOperator { operator: String },
    NotCallable { found: &'static str },
    WrongArity { expected: usize, found: usize },
    NotHashable { found: &'static str },
}

The public phase functions can now say what they do:

rust
fn parse_program(source: &str) -> Result<Program, Vec<ParseError>> {
    // lex, parse, and collect diagnostics
    # unimplemented!()
}

fn eval(program: &Program, env: Env) -> Result<Value, EvalError> {
    // evaluate with the runtime environment
    # unimplemented!()
}

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:

rust
fn eval_expr(expr: &Expr, env: &Env) -> Result<Value, EvalError> {
    match expr {
        Expr::Int(n) => Ok(Value::Int(*n)),
        Expr::Bool(b) => Ok(Value::Bool(*b)),
        Expr::String(s) => Ok(Value::String(s.clone())),
        Expr::Ident(name) => lookup(env, &name.name),
        Expr::Prefix { op, rhs } => {
            let value = eval_expr(rhs, env)?;
            eval_prefix(*op, value)
        }
        Expr::Infix { lhs, op, rhs } => {
            let left = eval_expr(lhs, env)?;
            let right = eval_expr(rhs, env)?;
            eval_infix(*op, left, right)
        }
        Expr::If { condition, consequence, alternative } => {
            let condition = eval_expr(condition, env)?;
            eval_conditional(condition, consequence, alternative.as_ref(), env)
        }
        Expr::Array(items) => items
            .iter()
            .map(|item| eval_expr(item, env))
            .collect::<Result<Vec<_>, _>>()
            .map(Value::Array),
        Expr::Function { params, body } => Ok(Value::Function {
            params: params.clone(),
            body: body.clone(),
            env: Rc::clone(env),
        }),
        Expr::Call { function, args } => {
            let callee = eval_expr(function, env)?;
            let args = args
                .iter()
                .map(|arg| eval_expr(arg, env))
                .collect::<Result<Vec<_>, _>>()?;
            apply(callee, args)
        }
    }
}

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:

rust
enum Flow {
    Value(Value),
    Return(Value),
}

fn eval_statement(stmt: &Statement, env: &Env) -> Result<Flow, EvalError> {
    match stmt {
        Statement::Return(expr) => Ok(Flow::Return(eval_expr(expr, env)?)),
        Statement::Expr(expr) => Ok(Flow::Value(eval_expr(expr, env)?)),
        Statement::Let { name, value } => {
            let value = eval_expr(value, env)?;
            env.borrow_mut().insert(name.name.clone(), value);
            Ok(Flow::Value(Value::Null))
        }
    }
}

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:

text
tokens → untyped AST → typed AST → runtime/compiler

A 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

  1. Write the phase diagram. Name the data crossing each arrow.
  2. Give domain concepts newtypes. Identifier, Span, HashKey, and Token prevent accidental interchange.
  3. Use enums for closed alternatives. Let the compiler enumerate the work when the language grows.
  4. Separate syntax from meaning. Keep Expr and Value distinct even when their cases look similar.
  5. Make expected failures data. Use Result with errors that preserve phase and location.
  6. Model non-local control explicitly. return, break, continue, and suspension should not hide inside ordinary values by accident.
  7. 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 Option for errors. None loses the reason parsing or lookup failed. Use Result when 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 return fall through. A return is a control-flow signal, not just another Value; 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


Back to Notes · see also OCaml - learning log · GADTs Through a Small Typed Expression Evaluator · Home.