Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Interpreter

Intent

Define a tiny language as composable expression objects, each able to evaluate itself in a shared context.

Motivation

A settings page lets power users type rules like “3 + x” where x is a live value. A tangle of string splits and special cases breaks the moment subtraction or nesting appears. Modeling each piece — numbers, variables, plus — as an expression that evaluates itself turns parsing into assembly and evaluation into one recursive call.

Structure

flowchart LR
  Client[Client] --> Expr[Expression]
  Expr --> Num[Number]
  Expr --> Var[Variable]
  Expr --> Add[Add]
  Add --> Expr
  Client --> Ctx[Context x=4]
  • Context — holds variable bindings (here x = 4) every expression can read.
  • Abstract Expression — the shared evaluate contract.
  • Terminal expressions (Number, Variable) — leaves with no children.
  • Nonterminal expression (Add) — combines child expressions and evaluates them.

Consequences

  • Benefit: each grammar rule is one small unit; extending the language means adding a unit, not rewriting a parser.
  • Cost: class count grows per rule, and interpretation is slower than compiled code — unsuitable for large or hot languages.

Basic Recap

Interpreter represents the grammar of a small language as expressions that can be evaluated in a context. Terminal expressions read values or constants, and nonterminal expressions combine child expressions according to language rules. Parsing builds the expression tree; evaluation interprets it without embedding language-specific branches throughout the client. This suits a bounded grammar, not the accidental creation of an unmaintainable general-purpose language.

Complex Scenario

A fraud review service lets analysts write a restricted rules language such as amount > limit and country in allowedCountries. A parser produces an abstract syntax tree, a validator checks fields and types, and expressions evaluate against one transaction context. Approved trees are cached so repeated decisions do not repeatedly parse the same rule text. Analysts can change rules without deploying the decision service, but they cannot execute arbitrary host code.

Edge cases

  • Concurrency: Immutable expression trees may be shared across evaluations, while transaction values and random or clock inputs must remain in a separate per-request context.
  • Memory pressure: Rule caching needs size limits, and deep or very wide expressions require depth and node-count validation before recursive evaluation exhausts the stack.
  • Partial failure: A missing risk-provider value should yield an explicit unknown or policy-driven outcome instead of being coerced to zero or false.

Evaluation must be deterministic within the supplied context, with a clear three-valued comparison policy if unknown values are part of rule decisions.

Sketch (illustrative pseudocode, not runnable):

AndExpression.evaluate(context):
    left = leftExpression.evaluate(context)
    if left == FALSE:
        return FALSE
    right = rightExpression.evaluate(context)
    return threeValuedAnd(left, right)

RuleEngine.decide(transaction):
    tree = ruleCache.getOrParse(ruleId, ruleText, limits)
    validator.assertApproved(tree)
    context = EvaluationContext(transaction, providerValues)
    return tree.evaluate(context).toDecision(policy)

When to Use / When Not to Use

Use when:

  • The language is tiny and stable (config rules, simple filters, demo arithmetic).
  • You want evaluation logic next to each rule for readability.

Avoid when:

  • The grammar is large, performance matters, or a real parser library already exists — use a parser instead.

Examples

  • examples/elixir/interpreter/
  • examples/dart/interpreter/
  • examples/go/interpreter/
  • examples/rust/interpreter/

Expected outcome: evaluating “3 + x” with x = 4 prints 7.

Anti-pattern / Failure Mode

  • Misuse: A full language where a data table or existing parser would do.

  • Review signal: Grammar changes forcing edits across every expression class.

  • Misuse symptom: New operators, statements, variables, and exceptions are added until a homemade interpreter becomes an untested programming language. Evaluating raw strings as host-language code to escape grammar maintenance is a severe security failure, not a convenient extension.

  • Review signal: Watch for expression classes that perform I/O, mutable variables stored in shared tree nodes, recursive evaluation with no depth guard, and grammar changes without parser and validation tests. If domain rules need full language tooling, use an established sandbox or embed a deliberately selected rules engine instead.

  • Visitor — evaluate a tiny language vs add operations over a structure.
  • Composite — expression trees are composites.
  • KISS — prefer the smallest language that works.

Exercise

Add a Subtract expression and evaluate “10 - x” with x = 4. Then add Multiply and check “3 + x * 2” — decide whether your parser handles precedence or evaluates left to right, and document it.

Self-check

  • Where do variables get their values?
    AnswerFrom the shared Context object passed into every evaluate call, not from the expression nodes themselves.
  • Terminal vs nonterminal: what differs?
    AnswerTerminal nodes are leaves (a number or variable lookup); nonterminal nodes hold child expressions and combine their results.
  • When should you NOT use Interpreter?
    AnswerFor a big or fast language — grammar growth explodes class count and tree-walking is slow; reach for a parser generator.