Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·10

Compilers and Runtimes

Companion to Volume 1, chapter 10: how the front end, the back end and runtimes connect; new angles (a court interpreter against a translated book, a recipe rewritten for a cook who can't read, a sentence diagram as a syntax tree, a stage manager as the JIT); what the chapter simplifies, from a 100,000-deep JSON document that crashes Python's parser to `String.matches` recompiling its regex a million times, `2 ** 3 ** 2` being 512, and one compiler flag changing a sum; the theory behind it (the Chomsky hierarchy, why some grammars are ambiguous, Rice's theorem for optimisers, the three Futamura projections); the JDK's regex compilation and `String.split` fast path; four debugging drills; interview questions with how to approach each.

6 sections · ~18 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 10 has three strands. The front end turns text into a checked tree: tokens, a parse tree, names resolved, types checked. The middle and back end turn that tree into an intermediate form, improve it, and emit machine code that the linker and loader assemble into a running program. Runtimes are the other half of the story: how code actually executes, from native machine code to bytecode that is interpreted and then compiled on the fly, with garbage collection underneath.

front end middle and back end runtimes lexing characters → tokens grammars, parsing tokens → tree abstract syntax trees the program as data name resolution which x is this? type checking reject before running errors lexical · syntax · semantic intermediate representations SSA · bytecode optimisation same meaning, less work code generation instructions · registers linking resolve symbols loading map into memory Java class loading lazy · verified native code compiled ahead bytecode VMs portable instructions interpreters run the tree or bytecode JIT compilation compile the hot paths AOT for managed languages start fast garbage collection reclaim what's unreachable feeds builds walked by then or reports rewritten by lowered by object files executables Java's way or runs by hot code to or ahead both need goes deeper: ch2 types and scopes · ch6 the bits code generation emits · ch7 what the instructions do · Volume 3 ch 35: the JVM exercises: P1–P12 build a lexer, parser and type checker, read bytecode, and watch the JIT
Concept map of chapter 10: the compiler front end (lexing, grammars and parsing, abstract syntax trees, name resolution, type checking), the middle and back end (intermediate representations and SSA, optimisation, code generation, linking and loading, Java's class loading) and runtimes (native code, bytecode virtual machines, interpreters, JIT and AOT compilation, garbage collection), with links such as type checking working on the AST and a JIT being a compiler that runs inside the runtime.

The links worth remembering:

  • Every language you use is a small compiler somewhere. Regular expressions compile to state machines (Code walkthrough), SQL to query plans, templates to code, JSON parsers to trees. The front-end ideas (tokens, grammars, bounded parsing) apply to all of them, and their bugs look the same (Gaps 1 and 2).
  • Optimisation must preserve meaning, and "meaning" is a specification. Compilers may reorder anything the language says can't be observed. Floating-point order can be observed, so it's preserved, unless you tell the compiler not to care (Gaps 4).
  • A JIT is a compiler inside the runtime. It has information an ahead-of-time compiler doesn't (which branches run, which types arrive) and pays for it in start-up time. Java's whole performance story is that trade.

Explain it differently

1. An interpreter is a court interpreter; a compiler is a translated book. The court interpreter translates each sentence live, every time it's spoken, so nothing needs preparing but every sentence costs translation time. A translated book is done once, slowly, and then read many times at full speed. A JIT is an interpreter who notices that the same few sentences keep coming up, writes down their translations, and from then on reads those from the card.

2. A syntax tree is the sentence diagram from school. "The cook who burned the dosa apologised" has a structure that the word order alone hides: the subject is "the cook who burned the dosa", and "apologised" goes with "cook", not with "dosa". Parsing recovers that structure, so that a - b * c means a - (b * c) and a - b - c means (a - b) - c. Precedence and associativity are the grammar's rules for drawing the diagram (Gaps 3).

3. Lowering to an IR is rewriting a recipe for a cook who can't read. "Make a tempering" is fine for an experienced cook. For a beginner, it becomes: heat 2 tbsp oil; add 1 tsp mustard seeds; wait until they pop; add curry leaves. Each step is simple, explicit and named. That's what an intermediate representation does: it turns rich source constructs into a small set of explicit steps, where each value has a name (SSA), so the optimiser can reason about them.

4. Optimisation is reorganising a kitchen without changing any dish. Moving the spice rack next to the stove, prepping onions once for three dishes, not boiling water nobody uses: dead-code elimination, common-subexpression elimination, loop-invariant hoisting. The rule is that every dish must taste exactly the same. When a "dish" depends on the exact order things were done (floating-point sums), reorganising is forbidden unless the customer says they don't mind (-ffast-math).

5. Linking is the wedding seating plan. Each table's card (an object file) says "seat for Ravi's uncle" without knowing which seat that is. The linker reads every card, finds where each person actually sits (resolves symbols), and fills in the numbers. A guest with no seat is an "undefined reference"; two guests claiming one seat is a "duplicate symbol". Java does this lazily: a class's references are resolved the first time each is used, which is why a missing class can surface hours after start-up as a NoClassDefFoundError (Chapter Exercises S4).

6. Garbage collection is housekeeping in a hotel. Rooms (objects) are cleaned once no guest holds a key (no reference reaches them). Generational collectors notice that most guests check out within minutes, so they clean the short-stay floor often and the long-stay floor rarely. A guest who keeps a key forever (a static map holding objects) keeps the room occupied, which is a memory leak in a garbage-collected language.

7. A regex is a tiny program you compile every time you forget to keep it. "d[0-9]{1,6}" is source code in a small language. Pattern.compile parses it into a graph of matching nodes; matcher().matches() runs that program. String.matches(regex) does both, every call, so writing it in a loop recompiles the program a million times (Gaps 2).

8. The JIT is a stage manager watching rehearsals. For the first performances, the stage manager just watches (interprets and profiles). Once a scene is clearly the same every night, they prepare it with shortcuts (compile with assumptions: "this variable is always an ArrayList"). If one night an actor improvises (a different type arrives), the shortcut is torn up (deoptimisation) and the scene is run carefully again until new assumptions are safe.

Gaps and misconceptions

What the chapter oversimplifies

1. "A recursive-descent parser follows the grammar": and the grammar allows any depth, but the stack doesn't. The chapter's parsers recurse once per nesting level. Grammars like JSON's allow unlimited nesting, so an input can be designed to exhaust the parser's stack. Real output:

Terminal
json.loads nesting    500: ok
json.loads nesting   1000: ok
json.loads nesting 100000: RecursionError: maximum recursion depth exceeded while decoding a JSON array from a unicode string
JS: JSON.parse nesting 100000: ok

Python's json module failed on a 200 KB document of brackets; Node's parser (in V8, not recursive in the same way) didn't. In Java, a recursive parser hits StackOverflowError, which many frameworks treat as fatal. Production parsers therefore enforce a maximum depth (Jackson's StreamReadConstraints defaults to a nesting depth of 1,000 since version 2.15; stage 10's rules parser does the same). A grammar describes valid inputs; a parser of untrusted input must also bound them.

2. "Regular expressions compile to automata": every String.matches call compiles again. The chapter (and Chapter Exercises) treat regexes as compiled programs. Java's convenience methods hide the compile step. A million dish ids checked three ways (JDK 21):

Terminal
1M ids: String.matches 197 ms | precompiled Pattern 52 ms | hand-written check 12 ms (all 1000000, 1000000, 1000000)

String.matches calls Pattern.compile on every call, about 4× slower than a precompiled Pattern, and a hand-written loop is another 4× faster. TiffinBox's own Dish constructor has used id.matches("d[0-9]{1,6}") since stage 2, so every dish created (and every order decoded from the log, every request parsed) recompiles that pattern. The TiffinBox build's stage 10 fixes it. String.split has a fast path that avoids regexes for simple separators (Code walkthrough), which is why split(",") is cheap and split(",\\s*") isn't.

3. "Precedence and associativity are fixed by the grammar": each language picks different ones. The chapter shows how a grammar encodes precedence. Real languages make different, sometimes surprising choices:

Terminal
Python: 2 ** 3 ** 2 = 512 | -2 ** 2 = -4 | not 1 == 2 -> True
JS: 2 ** 3 ** 2 = 512
JS: -2 ** 2 -> SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence

Exponentiation is right-associative (2 ** (3 ** 2)), unlike subtraction. In Python, -2 ** 2 is -(2 ** 2) = −4, because ** binds tighter than unary minus; JavaScript's designers found that so error-prone that they made it a syntax error instead. In C, == binds tighter than &, so flags & ACCEPTED == 0 means flags & (ACCEPTED == 0), which is always 0 (drill D3):

Terminal
flags=0x2 (not accepted): flags & ACCEPTED == 0 -> 0, (flags & ACCEPTED) == 0 -> 1

GCC warns with -Wall ("suggest parentheses around comparison in operand of '&'"); Java refuses to compile it at all, because int & boolean doesn't type-check. Language design is choosing where to put the trap, or whether to have one.

4. "Optimisations preserve the program's meaning": floating point is where you can opt out, and the results change. The chapter lists optimisations that are safe because they can't be observed. Reordering a floating-point sum can be observed (the Companion to chapter 06), so compilers don't, by default. Summing 10 million values in C with GCC 13:

Terminal
-O2: 1029999.9940249252 | -O3: 1029999.9940249252 | -O3 -ffast-math: 1029999.9940219107
exact (math.fsum): 1029999.9940000001

-O3 alone gives the same answer as -O2; -ffast-math permits reassociation, so GCC splits the sum into vector lanes (the assembly uses addpd, packed double additions), and the result changes in the ninth significant digit. Neither is "the right answer" (both differ from the exact sum); they're different answers, and the program's output now depends on a build flag. Java never does this: the JIT must preserve the source's order of floating-point operations (Java has been strict about this since Java 17's JEP 306).

Common misconceptions

Misconception What's actually true Where it's shown
"If the grammar accepts it, the parser handles it." Deep nesting exhausts a recursive parser's stack: bound the depth. Gaps 1; drill D1
"A regex in Java is compiled once." String.matches, replaceAll and multi-character split compile on every call. Gaps 2; drill D2
"Operator precedence is common sense." It differs between languages (**, unary minus, & and ==). Gaps 3; drill D3
"Higher optimisation levels give the same results, faster." Flags that relax floating-point rules change results. Gaps 4; drill D4
"Interpreted means slow, compiled means fast." A JIT compiles with run-time information and can beat AOT code on hot paths; an AOT binary starts faster. Explain it differently 1 and 8
"Garbage collection means no memory leaks." Anything still referenced is kept; leaks are references you forgot. Explain it differently 6

Theoretical gaps: the ideas behind the chapter

1. The Chomsky hierarchy: which tool parses which language. Languages form a ladder: regular languages (recognised by finite automata, so by true regular expressions), context-free languages (by pushdown automata, so by parsers with a stack), context-sensitive, and recursively enumerable. Balanced brackets are context-free but not regular, which is why no true regex can validate nested JSON or HTML, and why "parsing HTML with regex" is a famous mistake. Most programming languages are context-free at the grammar level, with context-sensitive rules (a variable must be declared before use) checked later, in semantic analysis.

2. Ambiguity is a property of grammars, and some languages can't avoid it. A grammar is ambiguous if one input has two parse trees: the classic "dangling else" (if a then if b then x else y: which if owns the else?). Grammars are made unambiguous by rules (precedence levels, "else binds to the nearest if"). Deciding whether an arbitrary context-free grammar is ambiguous is undecidable, so tools like parser generators report conflicts rather than proving absence of ambiguity. Parsing expression grammars (PEGs) sidestep ambiguity by making choice ordered: the first alternative that matches wins.

3. Perfect optimisation is impossible: Rice's theorem again. The Companion to chapter 01 introduced Rice's theorem: no program can decide any non-trivial property of what other programs compute. "Is this code dead?" and "do these two functions compute the same thing?" are such properties. So every optimiser is conservative: it optimises only what it can prove, and every new optimisation is a new proof technique (escape analysis, alias analysis). This is also why compilers rely on language rules to help: C's undefined behaviour (signed overflow can't happen) and Java's strict semantics both give the optimiser facts it couldn't prove otherwise.

4. The Futamura projections: a compiler is a specialised interpreter. Take an interpreter and a program, and partially evaluate the interpreter with the program fixed: the result runs the program without interpreting it, which is a compiled program (first projection). Specialise the partial evaluator to the interpreter, and you get a compiler (second); specialise it to itself, and you get a compiler generator (third). It sounds abstract, but GraalVM's Truffle framework works this way: language authors write an interpreter, and the system derives a JIT compiler from it.

5. Bootstrapping: compilers written in their own language. javac is written in Java, GCC in C and C++, Go's compiler in Go. The first version had to be compiled by something else; after that, each version compiles the next. Ken Thompson's "Reflections on Trusting Trust" (1984) showed the uncomfortable consequence: a compromised compiler can insert a backdoor into the next compiler's binary, with no trace in any source code. Reproducible builds (the TiffinBox build's stage 1) and "diverse double-compiling" are the modern defences.

6. Types are a static approximation of run-time behaviour. A type checker proves facts about all possible runs ("this is always a Money") without running the program. Because of Rice's theorem, it must reject some programs that would actually work: soundness (never accepting a program that goes wrong) costs completeness (accepting every program that wouldn't). Languages pick different points: Java's generics are erased and need casts at run time (Chapter Exercises P6); TypeScript's type system is deliberately unsound for convenience; Rust's borrow checker rejects safe programs it can't prove safe. Knowing which trade your language made explains its error messages.

Applying it

Code walkthrough

Two methods of java.lang.String show a runtime library deciding when to use its regex compiler. Excerpts from jdk-21-ga.

String.matches and Pattern.matches: compile, then run

java/lang/String.java:

Java
    public boolean matches(String regex) {
        return Pattern.matches(regex, this);
    }

java/util/regex/Pattern.java:

Java
    public static boolean matches(String regex, CharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

and the beginning of the compiler itself, in Pattern.compile():

Java
    private void compile() {
        // Handle canonical equivalences
        if (has(CANON_EQ) && !has(LITERAL)) {
            normalizedPattern = normalize(pattern);
        } else {
            normalizedPattern = pattern;
        }
        patternLength = normalizedPattern.length();

        // Copy pattern to int array for convenience
        // Use double zero to terminate pattern
        temp = new int[patternLength + 2];

        hasSupplementary = false;
        int c, count = 0;
        // Convert all chars into code points
        for (int x = 0; x < patternLength; x += Character.charCount(c)) {
            c = normalizedPattern.codePointAt(x);
            if (isSupplementary(c)) {
                hasSupplementary = true;
            }
            temp[count++] = c;
        }

Read it as the chapter's pipeline in miniature: compile() normalises the source, converts it into an array of code points (the "lexer" input, handling characters outside the BMP: the Companion to chapter 06's surrogate pairs), then parses it with a recursive-descent parser (expr, sequence, atom methods further down) into a graph of Node objects, which Matcher executes by walking. Every call to String.matches runs all of it: allocation of the work arrays, parsing, node construction. Nothing is cached. The fix is the programmer's: compile once into a static final Pattern.

String.split: a fast path that skips the regex compiler

Java
    private String[] split(String regex, int limit, boolean withDelimiters) {
        /* fastpath if the regex is a
         * (1) one-char String and this character is not one of the
         *     RegEx's meta characters ".$|()[{^?*+\\", or
         * (2) two-char String and the first char is the backslash and
         *     the second is not the ascii digit or ascii letter.
         */
        char ch = 0;
        if (((regex.length() == 1 &&
                ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
                (regex.length() == 2 &&
                        regex.charAt(0) == '\\' &&
                        (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
                        ((ch-'a')|('z'-ch)) < 0 &&
                        ((ch-'A')|('Z'-ch)) < 0)) &&
                (ch < Character.MIN_HIGH_SURROGATE ||
                        ch > Character.MAX_LOW_SURROGATE))
        {
            // All the checks above can potentially be constant folded by
            // a JIT/AOT compiler when the regex is a constant string.

Three ideas from this chapter in one if:

  1. Recognise a trivial program and skip the compiler. If the "regex" is a single ordinary character (","), or an escaped non-alphanumeric character ("\\|"), it can only mean "split on this one character", so split searches for that character directly with indexOf, without Pattern.
  2. Bit tricks instead of branches. ((ch-'0')|('9'-ch)) < 0 is true exactly when ch is outside '0'..'9': if ch is below '0', the first subtraction is negative; if above '9', the second is; OR-ing them makes the sign bit set if either is negative. One expression, no branches (the Companion to chapter 07's Code walkthrough uses the same style).
  3. Written for the JIT. The comment says it: when regex is a constant at the call site, the JIT can inline these checks and fold them to true or false at compile time, leaving only the fast loop. Library code is often shaped so that the optimiser can see through it.

Read it yourself

  1. Why does split("|") not take the fast path, and what does "a|b".split("|") return?
  2. Which of these take the fast path: split(","), split(", "), split("\\."), split("\\d")?

Debugging drills

D1. One API request takes down a worker

A partner integration accepts nested "combo" definitions as JSON. A security scan sent a 200 KB request consisting of 100,000 opening brackets, and the Python service's worker died. A reproduction:

Terminal
json.loads nesting 100000: RecursionError: maximum recursion depth exceeded while decoding a JSON array from a unicode string

Explain, and fix it at two levels.

D2. Order import got slower after adding validation

A CSV import validates each line with line.matches("^o[0-9]+,k[0-9]+,[0-9]+(\\.[0-9]{1,2})?$") and splits it with line.split(",\\s*"). Adding the validation doubled the import time. A measurement of just the id check:

Terminal
1M ids: String.matches 197 ms | precompiled Pattern 52 ms | hand-written check 12 ms (all 1000000, 1000000, 1000000)

Find both problems, and fix them.

D3. A kitchen tablet firmware never shows "not accepted"

Firmware written in C checks a status bit:

C
#define ACCEPTED 0x4
if (flags & ACCEPTED == 0) show("not accepted"); else show("accepted");

Every order shows "accepted", even ones the kitchen never accepted. A reproduction:

Terminal
flags=0x2 (not accepted): flags & ACCEPTED == 0 -> 0, (flags & ACCEPTED) == 0 -> 1

Explain, and say how the team should have caught it.

D4. The same C pricing library gives different totals on two servers

A native pricing library sums line amounts in double. The totals from the new build servers differ from the old ones in the last few digits, enough to fail reconciliation by a paisa now and then. Both run the same source. A reproduction of the difference:

Terminal
-O2: 1029999.9940249252 | -O3: 1029999.9940249252 | -O3 -ffast-math: 1029999.9940219107

Explain, and fix it properly.

Career-oriented

Interview prep

Mid level

Q1. What happens between writing int x = a + b * c; in Java and the CPU executing it?

How to get there. Walk the pipeline in order, naming the artifact at each stage: tokens, tree, checked tree, bytecode, then the runtime's path (interpret, profile, JIT-compile). Mention one decision made at each stage.

Q2. You need to let operations staff write simple rules ("free delivery if total ≥ ₹500 on weekdays"). Would you use a scripting engine, a JSON configuration, or a small custom language? Why?

How to get there. Compare the three on expressiveness, safety, tooling and maintenance. Show that a custom language is a compiler project, and say when it's worth it. Interviewers want a reasoned choice, not a favourite.

Senior level

Q3. After upgrading a library, a service's p99 latency rose 30% with no code change. The flame graph shows more time in java.util.regex. How do you investigate and fix it?

How to get there. Use the flame graph to find who calls regex, then check whether patterns are being compiled per call or whether a pattern's matching became expensive (backtracking). Fix by precompiling, simplifying or replacing the pattern, and prevent regressions.

Q4. Your team is designing a configuration format for kitchen workflows that will be edited by people and read by three services in two languages. What decisions matter most?

How to get there. Treat it as designing a small language: grammar (or schema), semantics, versioning, error reporting, and a single source of truth for parsing across languages. Draw on stage 6 (formats evolve) and this chapter (parsers must be strict and bounded).

Staff level

Q5. Several teams have each built a small rules or expression language for their product area. Should the company standardise on one? How would you decide?

How to get there. Inventory and compare (capabilities, users, quality, maintenance cost), consider the existing standards (CEL, JSONLogic, a SQL subset), and weigh migration cost against the benefit of shared tooling and skills. A staff answer includes a decision process and an exit for teams with real special needs.

Q6. Leadership asks whether moving the order service to GraalVM native images would cut cloud costs. How do you evaluate it?

How to get there. Separate start-up and memory gains (native images' strengths) from peak throughput (where the JIT often wins), map them to your actual costs (always-on services against scale-to-zero functions), and list the engineering costs (reflection configuration, build times, debugging).