Programming Search⌘K

Conceptcore

Compilers and interpreters

Also called compiler, interpreter, compilation, interpretation, ahead-of-time compilation, AOT, compile time, run time, virtual machine, transpiler.

A compiler translates a program into another language before it runs. An interpreter carries out a program as it reads it. Most systems mix both, with bytecode and JIT compilers.

Applies to
core-languages

Idea

A program is text, and a machine runs instructions, so something must bridge the two. A compiler translates the whole program, before it runs, into another language, usually machine code or a lower-level code for a virtual machine. An interpreter reads the program and carries out what it says, step by step, while it runs. Most language systems today mix the two: CPython compiles source to bytecode and interprets the bytecode, the JVM and JavaScript engines interpret bytecode and compile the hot parts to machine code while the program runs, and Go, Rust, C and C++ compile to machine code ahead of time.

# The program (x * 2 + 1) * x as a tree: (op, left, right), a name or a number.
tree = ("*", ("+", ("*", "x", 2), 1), "x")


def interpret(node, env):  # walk the tree every time the program runs
    if isinstance(node, int):
        return node
    if isinstance(node, str):
        return env[node]
    op, a, b = node
    x, y = interpret(a, env), interpret(b, env)
    return x + y if op == "+" else x * y


def compile_tree(node, code):  # translate the tree once into instructions
    if isinstance(node, int):
        code.append(("push", node))
    elif isinstance(node, str):
        code.append(("load", node))
    else:
        op, a, b = node
        compile_tree(a, code)
        compile_tree(b, code)
        code.append(("add",) if op == "+" else ("mul",))
    return code


def run(code, env):  # a virtual machine: a loop over instructions
    stack = []
    for ins in code:
        if ins[0] == "push":
            stack.append(ins[1])
        elif ins[0] == "load":
            stack.append(env[ins[1]])
        else:
            b, a = stack.pop(), stack.pop()
            stack.append(a + b if ins[0] == "add" else a * b)
    return stack.pop()


code = compile_tree(tree, [])
print(code)
for x in (1, 5, 10):
    print(interpret(tree, {"x": x}), run(code, {"x": x}))
Output
[('load', 'x'), ('push', 2), ('mul',), ('push', 1), ('add',), ('load', 'x'), ('mul',)]
3 3
55 55
210 210

The program holds the formula (x * 2 + 1) * x as a tree. interpret walks the tree each time it runs, deciding at every node what kind of node it is. compile_tree walks the tree once and emits a flat list of instructions for a small stack machine, and run executes that list in a loop. Both give the same results for every x. The compiled form does the analysis of the tree once, so each run only fetches and executes instructions.

How it works

The compiler pipeline. A compiler reads characters and groups them into tokens, parses the tokens into a syntax tree, checks names and types, translates the tree into an intermediate representation, improves that representation, and finally emits code for the target. The Rust book describes the result of compiling ahead of time: "Rust is an ahead-of-time compiled language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed."1 Each phase can reject the program, so a compiler finds syntax and type errors before the program runs at all. See abstract syntax trees.

Interpreters. A tree-walking interpreter evaluates the syntax tree directly, as interpret does. It is simple to write and starts at once, but it repeats the work of inspecting each node every time the node runs. A bytecode interpreter first compiles the tree into compact instructions for a virtual machine, then runs a loop that fetches, decodes and executes them. The V8 team names the cost that remains: "interpreters have inherent overheads that we can’t get rid of; things like bytecode decoding overheads or dispatch overheads that are an intrinsic part of an interpreter’s functionality."2 See tree-walking interpreters.

Bytecode and virtual machines. Many languages compile to an intermediate code and run it on a virtual machine. The Python glossary states: "Python source code is compiled into bytecode, the internal representation of a Python program in the CPython interpreter. The bytecode is also cached in .pyc files so that executing the same file is faster the second time".3 The bytecode separates the language from the machine: "The Java Virtual Machine knows nothing of the Java programming language, only of a particular binary format, the class file format."4 Kotlin, Scala and Clojure compile to the same class files, and F# and C# compile to the same intermediate language for .NET. See bytecode.

Just-in-time compilation. A JIT compiler translates code to machine code while the program runs. The .NET documentation describes the step: "At execution time, a just-in-time (JIT) compiler translates the CIL into native code."5 Engines such as V8 and HotSpot run new code in an interpreter first, count how often each function runs, and compile the hot functions with optimizing compilers. The optimizer can use what it has seen, such as the types that actually reach a function, and must undo the compiled code, called deoptimization, when that assumption stops holding. See just-in-time compilation.

Compile time and run time. Work that a compiler does happens once, before any user runs the program, and errors that it finds never reach a user. Modern compilers can run parts of the program itself: C++ constexpr and Rust const fn compute values during compilation. cppreference states: "The constexpr specifier declares that it is possible to evaluate the value of the entities at compile time."6 The cost moves from each run of the program to each build, and the rules for code that runs in the compiler are stricter, because it must be deterministic and free of undefined behavior.

Languages and implementations. Compiled and interpreted describe implementations, not languages. Python has CPython, a bytecode interpreter, and PyPy, a JIT compiler. C is almost always compiled, but C interpreters exist, and Cling runs C++ interactively. JavaScript was interpreted in its first engines and is JIT-compiled in all major engines today. What a language does fix is how much it lets a compiler know: static types, fixed layouts and no eval make good ahead-of-time code easier.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeThe TypeScript compiler checks types and emits JavaScript, which an engine then compiles and runs.
GoNative
RustNative
KotlinNativeCompiles to JVM bytecode, to JavaScript, or to native code through LLVM; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeThe database compiles each query into a plan, often caches the plan, and runs it with an interpreter or generated code.
BashNativeAn interpreter that reads and runs each command line; eval runs a string as commands.
PowerShellNativeCompiles script blocks to .NET expression trees and interprets them, compiling hot blocks; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyA browser parses markup into a tree; there is no program to compile.
CSSDoes not applyA browser parses style sheets into rules; there is no program to compile.
Regular expressionsNativeEngines compile a pattern into an automaton or a bytecode program before matching; several compile to machine code.
Language Verdict Mechanism
Python native CPython: bytecode compiler, .pyc cache and a virtual machine
JavaScript native bytecode interpreter and JIT tiers in the engine
TypeScript native compiles to JavaScript, which an engine runs
Java native javac to bytecode; the JVM interprets and JIT-compiles it
Kotlin native JVM bytecode, JavaScript or native code
C# native CIL in assemblies; JIT at run time or native AOT
Go native ahead of time to one executable
Rust native ahead of time through LLVM; const fn runs in the compiler
C native ahead of time to object files and a linker
C++ native ahead of time; templates and constexpr run in the compiler
Bash native an interpreter that reads and runs command lines
PowerShell native script blocks compiled to expression trees, interpreted then compiled
SQL native queries compiled to plans that the database runs
Regex native patterns compiled to automata or bytecode before matching
HTML n/a markup is parsed, not run
CSS n/a rules are parsed, not run

The core languages fall into three groups. Go, Rust, C and C++ compile ahead of time to machine code, so a program starts at full speed and needs no runtime compiler, but each change needs a build. Java, C# and Kotlin compile ahead of time to bytecode and then JIT-compile it, which keeps one binary for many machines and lets the runtime optimize for the actual workload. Python and JavaScript compile source to bytecode when a program starts, and JavaScript engines add JIT tiers on top.

Each example file shows the language compiling or interpreting code at a boundary that a program can see: Python code objects, the JavaScript Function constructor, the Java compiler as a library, C# expression trees, a Go parser used for an interpreter, a bytecode loop in C, and evaluation inside the compiler in Rust and C++. The fails blocks show errors that each system finds before the program runs.

PythonGitHub
source = "x * 2 + 1"
code = compile(source, "<formula>", "eval")  # source text to a code object
print(type(code).__name__, code.co_names)
print([eval(code, {"x": x}) for x in range(4)])  # run it many times


def area(w, h):
    return w * h


print(type(area.__code__).__name__, area.__code__.co_varnames)

namespace = {}
exec("def double(n):\n    return n * 2\n", namespace)  # compile a definition at run time
print(namespace["double"](21))
Output
code ('x',)
[1, 3, 5, 7]
code ('w', 'h')
42

This code does not compile, on purpose.

print("start")  # never runs: Python compiles the whole file first


def total(xs):
    return sum(xs)


def broken(
    return 0
  • Verdict: native. CPython compiles each module to bytecode before it runs any of it, caches the bytecode in .pyc files, and runs it on a virtual machine. compile turns source text into a code object at run time, eval and exec run it, and every function keeps its compiled code in __code__. Compiling once and running the code object many times avoids parsing the text again.
  • The fails block has a syntax error on its last line. Because CPython compiles the whole file first, the program stops with SyntaxError before the print on the first line runs.
#include <array>
#include <iostream>

constexpr unsigned long long fib(unsigned n) {
    unsigned long long a = 0, b = 1;
    for (unsigned i = 0; i < n; i++) {
        auto t = a + b;
        a = b;
        b = t;
    }
    return a;
}

constexpr auto table = [] {
    std::array<unsigned long long, 8> t{};
    for (unsigned i = 0; i < t.size(); i++) t[i] = fib(i);
    return t;
}();

static_assert(fib(10) == 55); // checked while the program compiles
static_assert(table[7] == 13);

int main(int argc, char**) {
    constexpr auto f50 = fib(50); // computed by the compiler
    std::cout << f50 << '\n';
    for (auto v : table) std::cout << v << (v == table.back() ? '\n' : ' ');
    std::cout << fib(argc + 9) << '\n'; // the same function at run time
}
Output
12586269025
0 1 1 2 3 5 8 13
55

This code does not compile, on purpose.

constexpr int divide(int a, int b) { return a / b; }

constexpr int ratio = divide(10, 0); // the compiler evaluates the call and rejects it

int main() { return ratio; }
  • Verdict: native. C++ compiles ahead of time to machine code, and much of the language runs inside the compiler: templates, constexpr functions and static_assert. A constexpr variable must get its value during compilation, so f50 and table cost nothing at run time, while the same fib can still run with a value known only at run time.
  • Undefined behavior is not allowed in a constant expression. The fails block divides by zero during constant evaluation, and the compiler rejects the program, where the same division at run time would be undefined behavior.
JavaGitHub
import java.lang.reflect.Method;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import javax.tools.ToolProvider;

public class Main {
    public static void main(String[] args) throws Exception {
        Path dir = Files.createTempDirectory("compile-demo");
        Path src = dir.resolve("Formula.java");
        Files.writeString(src, "public class Formula { public static int f(int x) { return x * 2 + 1; } }");

        var javac = ToolProvider.getSystemJavaCompiler(); // the compiler as a library
        int status = javac.run(null, null, null, src.toString());
        Path cls = dir.resolve("Formula.class");
        byte[] bytes = Files.readAllBytes(cls);
        System.out.printf("%d %X%n", status, ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16)
                | ((bytes[2] & 0xff) << 8) | (bytes[3] & 0xff)); // every class file starts with CAFEBABE

        try (var loader = new URLClassLoader(new java.net.URL[] {dir.toUri().toURL()})) {
            Method f = loader.loadClass("Formula").getMethod("f", int.class); // the JVM loads the bytecode
            System.out.println(f.invoke(null, 20));
        }

        try (var paths = Files.walk(dir)) {
            paths.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
        }
    }
}
Output
0 CAFEBABE
41
  • Verdict: native. javac compiles Java source to class files that hold bytecode for the JVM, and every class file starts with the bytes CAFEBABE. The JVM loads classes when the program first uses them, interprets their bytecode, and compiles hot methods to machine code with its JIT compilers.
  • The example uses the compiler as a library through javax.tools, loads the new class with a class loader, and calls its method through reflection. The command java Main.java does the same for a single source file: it compiles the file in memory and then runs it.
#include <stdio.h>

enum op { PUSH, LOAD, ADD, MUL, HALT };

struct ins {
    enum op op;
    int arg;
};

/* A bytecode interpreter: fetch an instruction, decode it, execute it. */
static int run(const struct ins *code, int x) {
    int stack[16], sp = 0;
    for (const struct ins *pc = code;; pc++) {
        switch (pc->op) {
        case PUSH: stack[sp++] = pc->arg; break;
        case LOAD: stack[sp++] = x; break;
        case ADD: sp--; stack[sp - 1] += stack[sp]; break;
        case MUL: sp--; stack[sp - 1] *= stack[sp]; break;
        case HALT: return stack[sp - 1];
        }
    }
}

/* The same formula compiled by the C compiler to machine code. */
static int native(int x) { return (x * 2 + 1) * x; }

int main(void) {
    const struct ins code[] = {{LOAD, 0}, {PUSH, 2}, {MUL, 0}, {PUSH, 1},
                               {ADD, 0},  {LOAD, 0}, {MUL, 0}, {HALT, 0}};
    for (int x = 1; x <= 10; x += 4) printf("%d %d\n", run(code, x), native(x));
    _Static_assert(sizeof code / sizeof code[0] == 8, "eight instructions"); /* checked at compile time */
    return 0;
}
Output
3 3
55 55
171 171
  • Verdict: native. A C compiler translates each source file to machine code in an object file, and a linker joins the object files and libraries into an executable. The preprocessor runs first, and _Static_assert lets the compiler check a condition before the program exists.
  • Many interpreters, including CPython and the Lua and Ruby virtual machines, are written in C around a loop like run: fetch an instruction, decode it with a switch, and execute it. The same formula compiled to machine code by the C compiler gives the same results without the dispatch work.
using System;
using System.Linq.Expressions;

var x = Expression.Parameter(typeof(int), "x");
var body = Expression.Add(Expression.Multiply(x, Expression.Constant(2)), Expression.Constant(1));
var tree = Expression.Lambda<Func<int, int>>(body, x); // code as a data structure
Console.WriteLine(tree);

Func<int, int> f = tree.Compile(); // compiled at run time to IL, then by the JIT to machine code
Console.WriteLine(f(20));

Expression<Func<int, int>> quoted = n => n * n; // the C# compiler builds the tree
Console.WriteLine($"{quoted.Body.NodeType} {quoted.Compile()(7)}");
Output
x => ((x * 2) + 1)
41
Multiply 49
  • Verdict: native. The C# compiler translates source to common intermediate language (CIL) in an assembly, and the runtime's JIT compiler translates each method to machine code the first time it runs. Ahead-of-time compilation to native code is also possible.
  • An expression tree is code held as data. A program can build one from nodes, or the C# compiler builds one from a lambda assigned to Expression<...>. Compile turns the tree into CIL at run time, and the JIT then compiles that, so a formula known only at run time runs as fast as code written by hand.
JavaScriptGitHub
const area = new Function("w", "h", "return w * h;"); // compile source at run time
console.log(area(3, 4), typeof area);

const formula = "x * 2 + 1";
const f = new Function("x", `return ${formula};`);
console.log([0, 1, 2, 3].map(f));

try {
  new Function("return (1 + ;");
} catch (e) {
  console.log(e.name); // the engine parses the source before it runs any of it
}

function hot(n) {
  let s = 0;
  for (let i = 0; i < n; i++) s += i; // a hot loop: the engine compiles it to machine code
  return s;
}
console.log(hot(1_000_000));
Output
12 function
[ 1, 3, 5, 7 ]
SyntaxError
499999500000
  • Verdict: native. A JavaScript engine parses the source, compiles it to bytecode for an interpreter, and compiles hot functions to machine code with one or more JIT compilers. The Function constructor and eval compile source text at run time, which is how template engines and some formula evaluators work. A syntax error in the text throws SyntaxError before any of the new code runs.
  • The engine watches hot as it runs the loop a million times, and moves it from the interpreter to compiled code. The program cannot see the change, except in speed.
package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"strconv"
)

// eval interprets a Go expression tree: a compiled program running an interpreter.
func eval(e ast.Expr, env map[string]int) int {
	switch n := e.(type) {
	case *ast.BasicLit:
		v, _ := strconv.Atoi(n.Value)
		return v
	case *ast.Ident:
		return env[n.Name]
	case *ast.ParenExpr:
		return eval(n.X, env)
	case *ast.BinaryExpr:
		a, b := eval(n.X, env), eval(n.Y, env)
		switch n.Op {
		case token.ADD:
			return a + b
		case token.SUB:
			return a - b
		case token.MUL:
			return a * b
		}
	}
	panic("unsupported expression")
}

func main() {
	expr, err := parser.ParseExpr("(x*2 + 1) * x")
	if err != nil {
		panic(err)
	}
	fmt.Printf("%T\n", expr)
	for _, x := range []int{1, 5, 10} {
		fmt.Println(x, eval(expr, map[string]int{"x": x}))
	}

	_, err = parser.ParseExpr("x * (2 +")
	fmt.Println(err != nil)
}
Output
*ast.BinaryExpr
1 3
5 55
10 210
true
  • Verdict: native. The Go toolchain compiles a program ahead of time to one machine-code executable, with the runtime and the garbage collector linked in. go run compiles to a temporary file and runs it, so it feels like an interpreter but is not one.
  • The standard library includes the Go parser, go/parser, which turns source text into a syntax tree. The example walks that tree to evaluate an expression: an interpreter inside a compiled program. A syntax error comes back as an error value, not a crash.
RustGitHub
const fn fib(n: u32) -> u64 {
    let (mut a, mut b) = (0, 1);
    let mut i = 0;
    while i < n {
        (a, b) = (b, a + b);
        i += 1;
    }
    a
}

const FIB_50: u64 = fib(50); // computed by the compiler, stored in the binary

const TABLE: [u64; 8] = {
    let mut t = [0; 8];
    let mut i = 0;
    while i < 8 {
        t[i] = fib(i as u32);
        i += 1;
    }
    t
};

fn main() {
    println!("{FIB_50}");
    println!("{TABLE:?}");
    let n: u32 = std::env::args().count() as u32 + 9; // known only at run time
    println!("{}", fib(n)); // the same function, called at run time
}
Output
12586269025
[0, 1, 1, 2, 3, 5, 8, 13]
55

This code does not compile, on purpose. The error is E0080.

const fn fib(n: u32) -> u8 {
    let (mut a, mut b) = (0u8, 1u8);
    let mut i = 0;
    while i < n {
        (a, b) = (b, a + b);
        i += 1;
    }
    a
}

const BIG: u8 = fib(20); // the compiler runs fib and finds the overflow

fn main() {
    println!("{BIG}");
}
  • Verdict: native. rustc compiles ahead of time, through LLVM, to a machine-code executable that runs without Rust installed. A const fn can run inside the compiler: FIB_50 and TABLE are computed during compilation and stored in the binary, and the same fib also runs at run time with an argument that the compiler cannot know.
  • The fails block computes a const whose evaluation overflows a u8. The compiler runs the function, finds the overflow, and rejects the program with E0080, so the error never reaches a user.
  • Transpilers. A source-to-source compiler translates one high-level language to another, such as TypeScript to JavaScript or Nim to C.
  • Ahead-of-time compilation of managed languages. GraalVM Native Image, .NET Native AOT and the Android runtime compile bytecode to machine code before the program runs, which cuts start-up time.
  • Tiered compilation. HotSpot, V8 and .NET run code in an interpreter or a fast compiler first, and recompile hot code with a slower optimizing compiler.
  • Tracing JITs. LuaJIT and PyPy record the operations of a hot loop as it runs and compile that trace.
  • Partial evaluation. Specializing an interpreter for one program yields a compiled program, an idea known as the Futamura projections. Truffle and PyPy build on it.
  • Read-eval-print loops. A REPL reads one expression, compiles or interprets it, and prints the result, which suits exploration. Lisp introduced it, and most languages now have one.
  • Compile-time execution. C++ templates and constexpr, Rust const fn and macros, and Zig comptime run code inside the compiler. See constant evaluation.
  • Language implementation. The parts of a compiler or interpreter, from lexing and parsing to code generation. See recursive descent parsing.

Pitfalls

  • Treating a language as compiled or interpreted. Speed and behavior depend on the implementation. Measure with the implementation you deploy.
  • Errors found late. An interpreter finds some errors only when it reaches the faulty line, and a JIT changes nothing about that. Run a type checker or linter, and keep tests that reach each path.
  • Warm-up. A JIT-compiled program runs slowly until its hot code is compiled, so a benchmark that runs for one second can measure the interpreter. Warm up before measuring, and use a benchmark harness.
  • Stale compiled output. A cached .pyc file, an old class file or a stale object file can make a program run old code. Let the build tool track dependencies, and clean the build when the results make no sense.
  • Running untrusted text as code. eval, exec and the Function constructor compile any text, so input from a user becomes code. Parse data with a parser for data, not with the language's compiler. See code injection.
  • Long builds. Heavy compile-time work, such as large templates and macro expansion, makes each build slow. Measure build time as you would run time.

Cost

A tree-walking interpreter often runs 10 to 100 times slower than optimized machine code for the same work, and a bytecode interpreter is often 3 to 30 times slower, the gap coming from dispatch and from values that carry their types. A JIT compiler closes most of that gap for hot code, at the cost of warm-up time, memory for compiled code and a compiler inside the runtime. Ahead-of-time compilation moves all of that cost to the build: compiling a large C++ or Rust program can take minutes, but the result starts at full speed with no compiler at run time.

History

Grace Hopper's A-0 system of 1952 translated symbolic code into machine code, and John Backus's team at IBM delivered the first FORTRAN compiler in 1957, which showed that compiled code could rival code written by hand. Steve Russell implemented John McCarthy's eval in 1958 to 1959 and so made the first Lisp interpreter. UCSD Pascal in the 1970s popularized p-code, a portable bytecode with an interpreter for each machine.

L. Peter Deutsch and Allan Schiffman compiled Smalltalk-80 bytecode to machine code at run time in 1984, and the Self project of the late 1980s and 1990s developed adaptive optimization and deoptimization. These ideas reached the mainstream in Sun's HotSpot JVM in 1999 and Google's V8 JavaScript engine in 2008.2 Chris Lattner began LLVM in 2000, and it became the back end of Clang, Rust and Swift. C++11 added constexpr in 2011, and later standards and Rust's const fn moved more of the program into the compiler.6

References

  1. Hello, World!, The Rust Programming Language, Compilation and Execution
  2. Sparkplug, a non-optimizing JavaScript compiler, V8 blog, Introduction
  3. Glossary, Python documentation, bytecode
  4. Chapter 1, Introduction, The Java Virtual Machine Specification, Java SE 25 Edition, 1.2 The Java Virtual Machine
  5. Managed execution process, .NET documentation, Microsoft Learn, Compile CIL to native code
  6. constexpr specifier, cppreference.com, Explanation

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BM299A/text.yaml