← Runtimes
Runtimes

Compilation and interpretation

What is done once before running, and what is done every time.

Compilation translates a program before its instructions execute; interpretation carries out a representation of the program as it runs.

Outcome

Say which work a compiler does once and an interpreter repeats, predict whether a mistake is reported before running or only when its code runs, and move only value-independent work to compile time.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Interpreter
A program that carries out another program’s operations directly, as it reaches them.
Compiler
A program that translates code into another form before that translated code executes. JIT compilation can happen inside a running process.
Virtual machine
An implementation of an instruction set. The lab uses an interpreter for the instructions its compiler emits.
Slot
A numbered storage location a compiler assigns to a variable, so running code needs no name lookup.
Constant folding
Computing, at compile time, an operation whose operands are all constants.
JIT compilation
Compiling code to machine code while the program runs, as V8 does for hot functions.

When work happens

Parsing gives source a structure, and checking can establish facts about it. Compilation translates that structure into another form, such as bytecode or machine code. An interpreter executes a representation directly. One implementation can combine these strategies at different stages.

The useful decision is which work depends only on the rule and which work needs current inputs. A reusable fee rule can resolve a variable name to a storage slot once, but must read the rate from that slot whenever it calculates a new quote. Translation and checking do not establish every property of the values supplied later.

01Before running

When is a misspelled name caught?

A parcel service wants to catch mistakes before activating a fee rule, then reuse that rule while parcel weights and rates change. Compilation can settle names and translate operations ahead of their execution. The resulting code still needs current inputs. A small rule engine lets us separate those decisions; real toolchains combine interpretation, compilation and static analysis.

The fee check must cover the heavy-parcel branch before the service activates the rule. Each selected checker resolves its misspelled name even if no light-parcel test reaches it. A runtime that defers this particular lookup can fail only when execution reaches it.

Each program computes a parcel fee. The branch for heavy parcels misspells weight; the first call takes the light branch.

tsc checks the whole program before node runs anything.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A parcel fee with a misspelled name in the branch for heavy parcels.

function fee(weight: number): number {
  if (weight > 1000) {
    return wieght * 2;
  }

  return 5;
}

console.log(`light parcel: ${fee(200)}`);
console.log(`heavy parcel: ${fee(1500)}`);
What happens when you run the command?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

Read each source and predict the selected command’s result before revealing the recorded build notes. The typo probes are rejected before execution. The C++ division probe has undefined behavior; its historical output is not an experiment to rely on.

02While running

What does acceptance leave unchecked here?

Before trusting the fee check as a complete safety test, try a smaller value-domain probe: splitting a bill by a reply count. All four recorded builds accept it. Acceptance does not prove a nonzero divisor. Compilers can evaluate constants and prove some value properties, but these checks do not reject this division.

Each program splits a bill between the guests who replied. Nobody has; the Rust command supplies no arguments. This reduced probe isolates division behavior, independently of the parcel rule.

replies.length is a number; JavaScript numbers are floating point.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Splits a bill between the guests who replied; nobody has replied yet.

const replies: string[] = [];
const bill = 90;

console.log(`each pays: ${bill / replies.length}`);
The program compiles. What happens when it runs?

03Strategies

What does each strategy do once, and what every time?

The service will quote many parcels with the same saved rule. Our lab’s naive walker revisits expression nodes and searches for names each time. Its compiler resolves names to numbered slots and emits VM instructions once. Running those instructions still reads the slots’ current values.

Common selected toolchain pipelines; not fixed language categories
LanguageBefore runningWhile running
TypeScripttsc checks types and emits JavaScriptV8 parses, interprets bytecode, compiles hot functions to machine code
GoCompiles to a native binaryMachine code, plus the Go runtime (scheduler, collector)
RustCompiles to a native binaryMachine code
C++Compiles and links to a native binaryMachine code
In the lab’s naive tree walker and slot compiler, a rule is evaluated a million times. Which work does the compiler do once that the walker repeats?

04Practice

Finish the rule engine

Use a small arithmetic rule engine for the parcel service. First make previews skip untaken work. Then reject unknown names before activating compiled code. Finally keep a rule for later quotes, folding literal arithmetic while preserving inputs that can change. The supplied parser and VM are authored teaching models, not reconstructions of the four native toolchains.

The rule engine

Walk only the branch taken, resolve names while compiling, then fold constants once.

  1. easy · R-RULES-V4-1 Walk only the branch taken
  2. medium · R-RULES-V4-2 Resolve names while compiling
  3. hard · R-RULES-V4-3 Fold constants once
In the frontend A built quote preview still reads changing state Optional

The parcel quote preview is already built. Initially weight is 4 and rate is 2. Predict the displayed fee after clicking Raise rate once: does the build fix the result at 14, or does the component show 18?

This diagnostic uses ordinary function calls and state. It does not implement the lab’s parser, name resolver or constant folder.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
'use client';
import { useState } from 'react';

function fee(weight: number, rate: number): number {
  return weight * rate + 2 * 3;
}

export default function Quote() {
  const [rate, setRate] = useState(2);
  return (
    <div>
      <p>Fee: {fee(4, rate)}</p>
      <button onClick={() => setRate(rate + 1)}>Raise rate</button>
    </div>
  );
}

The next render passes rate 3, giving 18. Erasing TypeScript annotations does not capture the initial state value in fee. An optimizer may fold the literal product 2 * 3; correctness still requires the result to reflect the current arguments.

Sources: TypeScript: erased types,React: useState,Svelte: $state.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.