20. Source Maps & Debugging
Mapping compiled code back to source
Your compiler works. It takes source code, parses it into an AST, and emits
bytecode that a VM executes. But then the VM hits a runtime error at instruction
47 and reports: Error at ip=47. That's useless. The programmer wrote source
code, not bytecode. They want to see: Error at line 12, column 5.
This is the source mapping problem: how do you connect generated code back to the original source? It sounds like bookkeeping — and it is — but getting it right is the difference between a toy compiler and one people can actually use.
The problem
Compilation is a lossy transformation. Variable names become stack slots. Nested expressions become flat instruction sequences. A single source line might produce five bytecode instructions, and two adjacent instructions might come from lines that are 30 lines apart in the source.
Source: Bytecode:
0: OP_CONST 10
let x = 10; 1: OP_SET_LOCAL 0
2: OP_CONST 20
let y = 20; 3: OP_SET_LOCAL 1
4: OP_GET_LOCAL 0
5: OP_GET_LOCAL 1
print x + y; 6: OP_ADD
7: OP_PRINT
If OP_ADD at offset 6 throws an error (say, one operand is a string), you need
to tell the user it happened on line 3 of their source. The bytecode itself
doesn't contain that information — unless you record it during compilation.
Line tables
The simplest and most common approach is a line table: an array where entry stores the source line number for bytecode instruction .
class LineTable {
constructor() {
this.lines = []; // lines[i] = source line for instruction i
}
add(line) {
this.lines.push(line);
}
getLine(offset) {
return this.lines[offset] ?? null;
}
}
Every time the compiler emits an instruction, it also records which source line it came from:
class Compiler {
constructor() {
this.code = [];
this.lineTable = new LineTable();
this.currentLine = 1;
}
emit(opcode, operand = null) {
this.code.push(opcode);
this.lineTable.add(this.currentLine);
if (operand !== null) {
this.code.push(operand);
this.lineTable.add(this.currentLine);
}
}
compileLet(node) {
this.currentLine = node.line; // update from AST node
this.compileExpression(node.value);
this.emit(OP_SET_LOCAL, node.slot);
}
}
The key insight: every AST node already knows its source position (the parser recorded it during parsing). The compiler just copies that information into the line table as it emits instructions.
Using line tables for error messages
With a line table, error messages become useful:
class VM {
run() {
while (this.ip < this.code.length) {
try {
this.step();
} catch (e) {
const line = this.lineTable.getLine(this.ip);
throw new RuntimeError(
`${e.message} [line ${line}]`
);
}
}
}
}
Instead of "TypeError: cannot add string and number", the user sees "TypeError: cannot add string and number [line 12]". With a bit more work, you can include the column and even show the offending source line:
TypeError: cannot add string and number
at line 12:
print x + y;
^
This requires keeping the original source text (or at least the relevant lines) around at runtime, but it's worth it.
Compressing the line table
A naive line table — one entry per byte of bytecode — can get large. If your program has 10,000 bytes of bytecode, that's 10,000 line entries. But most consecutive instructions come from the same line.
A run-length encoded line table compresses this dramatically:
class CompressedLineTable {
constructor() {
this.runs = []; // [{count, line}, ...]
}
add(line) {
const last = this.runs[this.runs.length - 1];
if (last && last.line === line) {
last.count++;
} else {
this.runs.push({ count: 1, line });
}
}
getLine(offset) {
let pos = 0;
for (const run of this.runs) {
pos += run.count;
if (offset < pos) return run.line;
}
return null;
}
}
The line let x = 10; might produce 3 instructions, all from line 1. Instead of
storing [1, 1, 1], the compressed table stores a single run: {count: 3, line: 1}.
In practice, this shrinks the table by 60-80%.
Python's .pyc files, Lua's compiled chunks, and the JVM's .class files all
use variations of this approach.
Column information
Line numbers are usually enough, but sometimes you need the column too — especially when a single line contains multiple expressions:
let result = foo(x) + bar(y) * baz(z);
// ^ ^ ^
// col 14 col 24 col 34
If bar(y) throws an error, "line 1" isn't precise enough. You want "line 1,
column 24." To support this, extend the line table to store {line, column}
pairs instead of just line numbers. The cost is double the storage, so some
compilers only record columns in debug builds.
The JavaScript source map format
The web ecosystem solved this problem at a different scale. TypeScript, Babel, and minifiers like Terser all transform JavaScript before it reaches the browser. The standard source map format lets browser DevTools show the original code.
A source map is a JSON file:
{
"version": 3,
"file": "bundle.min.js",
"sources": ["app.ts", "utils.ts"],
"names": ["greet", "name", "console", "log"],
"mappings": "AAAA,SAASA,GAAGC,GACVC,QAAQC,IAAI..."
}
The mappings field is the interesting part. It's a string of
VLQ-encoded
segments, where each segment maps a position in the generated file to a position
in an original file.
Each segment encodes four (sometimes five) values:
- Generated column (relative to the previous segment)
- Source file index (into the
sourcesarray) - Original line (relative to the previous segment)
- Original column (relative to the previous segment)
- Optionally, a name index (into the
namesarray)
The VLQ encoding keeps the mapping compact. A segment like AAAA decodes to
four zeros, meaning "same column, same source, same line, same column as before."
A segment like KACF decodes to relative offsets that shift the position.
How browsers use source maps
When you open DevTools and see your original TypeScript instead of minified JavaScript, source maps are doing the work:
- The generated JS file contains a comment:
//# sourceMappingURL=bundle.js.map - DevTools fetches the
.mapfile - When you click a line in the Sources panel, DevTools looks up the generated position in the mappings and shows you the original source
- When you set a breakpoint on original line 12, DevTools maps it to the corresponding generated position and tells the JS engine to break there
The developer never sees the generated code — they debug the original.
Breakpoints
A breakpoint is conceptually simple: the user says "stop at line 15," and the debugger makes it happen. But the VM executes bytecode, not source lines. So the debugger needs to:
- Look up line 15 in the line table
- Find the first bytecode offset that corresponds to line 15
- Insert a trap at that offset
class Debugger {
constructor(vm) {
this.vm = vm;
this.breakpoints = new Set(); // set of bytecode offsets
}
setBreakpoint(line) {
// Find the first instruction on this line
for (let i = 0; i < vm.lineTable.lines.length; i++) {
if (vm.lineTable.getLine(i) === line) {
this.breakpoints.add(i);
return i;
}
}
return null; // no code on that line
}
shouldBreak(ip) {
return this.breakpoints.has(ip);
}
}
In the VM's main loop, you check before each instruction:
while (this.ip < this.code.length) {
if (debugger.shouldBreak(this.ip)) {
debugger.pause(this); // hand control to the debugger UI
}
this.step();
}
When the debugger pauses, it can inspect the VM's stack, local variables, and environment. The developer sees their source code with the current line highlighted, along with the values of all variables in scope.
Single-stepping
Once paused, the developer often wants to step one source line at a time. But one source line might correspond to multiple bytecode instructions. The debugger handles this by recording the current source line and running instructions until the line changes:
class Debugger {
stepLine(vm) {
const startLine = vm.lineTable.getLine(vm.ip);
do {
vm.step();
} while (
vm.ip < vm.code.length &&
vm.lineTable.getLine(vm.ip) === startLine
);
// Now we're on a new source line — pause again
}
}
This is "step over" — it advances to the next line in the current function. "Step into" would additionally check whether the current instruction is a function call and, if so, follow it. "Step out" would run until the current function returns.
Stack traces
When an error occurs deep in a call chain, you want a stack trace — not just the current line, but the full chain of calls that led there.
The VM's call stack already contains return addresses (the bytecode offsets to return to after each function call). To build a stack trace, walk the call stack and resolve each return address through the line table:
function stackTrace(vm) {
const frames = [];
// Current position
frames.push({
fn: vm.currentFunction.name,
line: vm.lineTable.getLine(vm.ip),
});
// Walk call frames
for (let i = vm.callStack.length - 1; i >= 0; i--) {
const frame = vm.callStack[i];
frames.push({
fn: frame.function.name,
line: frame.lineTable.getLine(frame.returnAddress),
});
}
return frames;
}
This produces the familiar output:
Error: division by zero
at divide (line 3)
at calculate (line 12)
at main (line 20)
Each frame shows the function name and the source line — exactly the information a developer needs to diagnose the problem.
The full picture
Source mapping connects two worlds: the world of generated code (fast, compact, machine-friendly) and the world of original source (readable, debuggable, human-friendly). The pieces are:
- Line table — maps bytecode offsets to source lines, recorded during compilation
- Error messages — resolve the current instruction pointer to a source position
- Breakpoints — resolve a source line to a bytecode offset, insert a trap
- Single-stepping — run instructions until the source line changes
- Stack traces — walk the call stack, resolving each return address
Without source maps, a compiler is a black box. With them, it's transparent — the developer sees through the generated code to the source they actually wrote.
Next, we'll go all the way back to the beginning — to the language family where the AST is the syntax, and parsing is almost trivially simple: S-expressions and Lisp.
Try It Yourself — Source Map Explorer
Type a short program below. The compiler will produce bytecode and a line table. Click on a bytecode instruction to highlight the source line it came from, or click a source line to see which instructions it generated.