Search

Search papers and lessons

Interpreter

Level 2 · 10 min read

An interpreter runs a program by walking its syntax tree and carrying out each part directly, so it produces results without first translating the whole program into [[machine-code|machine code]].

On this page

  • Colour = topic mix
  • Discrete math
  • Programming languages
  • Systems
  • Algorithms
  • ReadReady to readNot yet

TL;DR

An interpreter is a program that reads another program and carries out its instructions itself, one piece at a time. It usually parses the source text into an Abstract Syntax Tree, then walks that tree and computes the value of each part. It solves the problem of running a language without a separate translation step, which makes it quick to start, easy to change and portable to any machine that has the interpreter.

Builds on: Abstract Syntax Tree, Lexical Scope · Leads to: Compiler, Closure

Where it's used

Scripting and shells. When you type a command in a shell such as bash, a program reads the line, works out what each word means and carries out the command at once. Nothing is translated to a file that runs later. This is the interpreter pattern in its most direct form.

Python. The standard Python implementation, CPython, first turns source code into a compact list of instructions called bytecode, and then runs that bytecode in a loop that handles one instruction at a time. The loop is an interpreter. The bytecode step is a compile step, so the two ideas are often combined.

JavaScript engines. V8, the engine used in Chrome and Node.js, runs JavaScript through an interpreter called Ignition that executes bytecode. Code that runs many times is later compiled to faster machine code. The interpreter gets the program running immediately, and the compiler speeds up the parts that matter.

Domain languages. Spreadsheet formulas, regular-expression engines, query languages and configuration templates are often interpreted. Each is small enough that a direct walk over its syntax tree is fast enough, and users get an answer as soon as they type.

How it works

Follow one tiny expression through an interpreter. The program is the text 1 + 2 * 3.

  1. Read the text. The interpreter receives the characters 1, +, 2, *, 3, and a lexical analysis step groups them into tokens: three numbers and two operators. Check: five symbols, three numbers and two operators.
  2. Parse into a tree. Multiplication binds tighter than addition, so 2 * 3 groups first. The binary tree has + at the root, with the leaf 1 on the left and a * node on the right. That * node has the leaves 2 and 3. Check: the tree's shape encodes the precedence, so no brackets are needed in the tree.
  3. Visit the root. The interpreter sees a + node. It must know the value of both children before it can add them. It starts with the left child. Check: the left child is the leaf 1, whose value is 1.
  4. Visit the right child. This is a * node. Its children are the leaves 2 and 3, with values 2 and 3. Multiply them: 2 × 3 = 6. Check: the value of the * node is 6.
  5. Combine at the root. Now both children of + have values: 1 and 6. Add them: 1 + 6 = 7. Check: the value of the whole program is 7, and the interpreter did no work that was not in the tree.

The output is 7. Nothing was written to disk and no machine code was produced. The interpreter visited each node once, computed its value from its children, and passed the result upward.

flowchart TD
  P["+ (root)"] --> L["1"]
  P --> M["*"]
  M --> T["2"]
  M --> R["3"]

The math

A program that is a tree of nested expressions can be described as a function. Let nn be a node of the tree and let ρ\rho be an environment, meaning a table that maps variable names to their current values. The interpreter is a function eval(n,ρ)\mathrm{eval}(n, \rho) that returns the value of nn. It is defined by cases:

eval(n,ρ)={cif n is a number literal c,ρ(x)if n is a variable x,apply(op,  eval(a,ρ),  eval(b,ρ))if n is an operator op with children a and b.\mathrm{eval}(n, \rho) = \begin{cases} c & \text{if } n \text{ is a number literal } c, \\ \rho(x) & \text{if } n \text{ is a variable } x, \\ \mathrm{apply}\big(\mathrm{op},\; \mathrm{eval}(a, \rho),\; \mathrm{eval}(b, \rho)\big) & \text{if } n \text{ is an operator } \mathrm{op} \text{ with children } a \text{ and } b. \end{cases}

In words: a number evaluates to itself, a variable evaluates to what the environment says, and an operator evaluates its two children first and then applies the operation to their values. The recursion is on the tree: each call works on a smaller subtree, and the base cases are the leaves.

Step 2 in symbols: the leaves

For the leaf 11, the first case applies, so eval(1,ρ)=1\mathrm{eval}(1, \rho) = 1. The same holds for 22 and 33.

Step 3 in symbols: the root

Let the root be ++ with children a=1a = 1 and b=∗(2,3)b = *(2, 3). Then

eval(+,ρ)=apply(+,eval(1,ρ),eval(∗(2,3),ρ)).\mathrm{eval}(+, \rho) = \mathrm{apply}\big(+, \mathrm{eval}(1, \rho), \mathrm{eval}(*(2,3), \rho)\big).

Step 4 in symbols: the subtree

The right child is evaluated by the third case with op=∗\mathrm{op} = *:

eval(∗(2,3),ρ)=apply(∗,2,3)=6.\mathrm{eval}(*(2,3), \rho) = \mathrm{apply}(*, 2, 3) = 6.

Step 5 in symbols: the combination

Substituting back, eval(+,ρ)=apply(+,1,6)=7\mathrm{eval}(+, \rho) = \mathrm{apply}(+, 1, 6) = 7.

The same definition handles variables. If ρ={x↦3}\rho = \{x \mapsto 3\}, then eval(x,ρ)=3\mathrm{eval}(x, \rho) = 3, and the expression x⋅x−4x \cdot x - 4 is evaluated as apply(−,apply(⋅,3,3),4)=9−4=5\mathrm{apply}(-, \mathrm{apply}(\cdot, 3, 3), 4) = 9 - 4 = 5. How ρ\rho is built for nested blocks follows the rules of Lexical Scope: the lookup for a name starts in the innermost environment and moves outward.

Worked examples

Example
Tiny: a sum of two numbers

The program is 2 + 3.

  1. Parse: a + node with leaves 2 and 3.
  2. Evaluate the left leaf: eval(2)=2\mathrm{eval}(2) = 2.
  3. Evaluate the right leaf: eval(3)=3\mathrm{eval}(3) = 3.
  4. Apply addition: 2+3=52 + 3 = 5.

Interpretation: the interpreter reduces the tree to one value, and the answer is 5. There is no subtree to recurse into, so the whole computation is one step.

Example
Standard: brackets change the shape of the tree

The program is (2 + 3) * 4. The brackets force addition to happen first, so the root is *.

  1. Parse: the root is *, its left child is a + node with leaves 2 and 3, and its right child is the leaf 4.
  2. Visit the left child, a + node. Its leaves give 2+3=52 + 3 = 5.
  3. Visit the right child, the leaf 4, with value 4.
  4. Apply multiplication at the root: 5×4=205 \times 4 = 20.
  5. Interpretation: the same tokens 2, 3, 4, +, * produce 20 here, but 2 + 3 * 4 would give 14. The tree, not the reading order of the text, decides what happens first.

Compare with 2 + 3 * 4. The root is now +, with a * node on the right. The * node gives 3×4=123 \times 4 = 12, then 2+12=142 + 12 = 14. This is the reason parsers build a tree before evaluating: the tree already encodes precedence.

Example
Realistic: a calculator with a variable

A small spreadsheet-like tool stores one named value in its environment, rate = 4, and evaluates the formula rate * (10 - 2). The tree has root *, with the variable rate on the left and a - node on the right whose leaves are 10 and 2.

  1. Look up the environment: ρ(rate)=4\rho(\text{rate}) = 4.
  2. Visit the right child, the - node. Its leaves give 10−2=810 - 2 = 8.
  3. Apply multiplication at the root: 4×8=324 \times 8 = 32.
  4. Interpretation: the formula is evaluated fresh every time the user changes rate, which is why a formula cell can update instantly. An interpreter does this cheaply because it only walks the tree again.

Try it: evaluate 10 - 2 * (3 + 1) by building the tree first. Answer: the root is -, with leaf 10 on the left and a * node on the right. The * node has leaf 2 and a + node whose leaves are 3 and 1. Evaluate 3+1=43 + 1 = 4, then 2×4=82 \times 4 = 8, then 10−8=210 - 8 = 2.

Common mistakes and tradeoffs

It is tempting to think that an interpreter and a compiler are two different kinds of program that never overlap. In fact many systems do both: CPython compiles source to bytecode and then interprets it, and V8 interprets bytecode before compiling hot code to machine instructions. The distinction is about when and how the work is done, not a fixed property of the language.

It is tempting to think that interpreted languages are always slow. In fact the cost of an interpreter comes from walking the tree and dispatching on each node at run time. A well-designed interpreter can be fast enough for most uses, and a JIT compiler can recover much of the speed later. The slowdown is real, but it is a tradeoff rather than a rule.

It is tempting to think that the interpreter must parse the same text again on every run. In fact most interpreters parse once to a tree or bytecode and keep it in memory, so the repeated work is only the evaluation. Re-parsing each time is a special choice that some simple tools make on purpose.

Use an interpreter when you need quick startup, a simple implementation, easy debugging, portability to many machines, or a language that users change while the program runs. Avoid it when the program runs many times on the same input and speed matters, or when you must ship a standalone binary. Alternatives include compiling to machine code (Compiler), compiling to bytecode for a virtual machine, and mixing both with a just-in-time compiler.

History

Early programs were written in machine code or assembly, and the first widely used high-level languages were compiled. The first FORTRAN compiler was delivered in 1957, and the idea that a translator must produce machine code before anything can run became the default for a while.

Interpreters took a different path. Around 1958 to 1960, John McCarthy and his collaborators developed LISP and showed that a LISP interpreter could be written in LISP itself, using a small eval function that walked the expression tree. That demonstration made the interpreter a clear, teachable idea and a practical way to build languages.

Interpreters caught on for scripting and for teaching because they were easy to write and to change. Later, the desire for speed led to hybrid designs that interpret first and compile later, which is the approach used by many modern language runtimes.

Recap

  • An interpreter runs a program by walking its syntax tree and computing the value of each part directly.
  • The tree comes from parsing with a grammar, which encodes precedence, so the evaluation order is determined by the shape of the tree, not by reading left to right.
  • Each node is evaluated from its children, and variables are looked up in an environment whose rules follow Lexical Scope.
  • Interpreters trade run-time speed for quick startup, simplicity and portability, and many real systems combine interpretation with Compiler techniques.
  • Read next: Closure shows how an interpreter keeps the environment of a function alive after the function that created it has returned.

Check yourself

QuestionRecall: what does an interpreter do with a number literal such as 7 in the tree?Show answer

It returns the number itself. A literal is a leaf of the tree, and its value is part of the program text, so the first case of the definition gives eval(7,ρ)=7\mathrm{eval}(7, \rho) = 7 without looking at the environment.

QuestionComputation: what does the interpreter output for the tree of `4 * (2 + 5)`?Show answer

The root is * with leaf 4 on the left and a + node on the right. The + node gives 2+5=72 + 5 = 7. Then 4×7=284 \times 7 = 28. The output is 28.

QuestionWhy: why does the interpreter need a tree rather than evaluating the characters from left to right?Show answer

Operators have precedence and brackets change grouping. Reading 2 + 3 * 4 from left to right would give 20 if each operator were applied in turn, but the correct answer is 14. The tree records that * groups first, so evaluating children before parents gives the right result. The tree encodes the grouping that the text expresses with precedence rules and brackets.

QuestionApplied scenario: a teaching tool re-parses the source text of a program each time the user changes one input, and users complain it is slow. What is the likely fix, and why does it work?Show answer

Parse the text once into a tree and keep the tree in memory. Each new input then needs only an evaluation walk, which is the cheap part. The parse is the expensive step to repeat, and caching the tree removes it while leaving the result unchanged, because the program text has not changed.

Sources