COMPILER PIPELINE
From source text to machine code in stages
n is an int, s is a string, and the pipeline skips type checking. Codegen, the last stage, picks machine instructions and emits ADD for every + it has no type for. What does let z = n + s; produce?
A compiler is a chain of stages, each with one job. The lexer turns characters into tokens and rejects a character that fits no token. The parser turns tokens into a tree (the AST) and rejects tokens that break the grammar. Both report a line and column. The type checker gives every expression a type and rejects operations that do not fit, such as adding an int to a string. Codegen comes last. It picks instructions from those types and assumes every check before it already passed.
function compile(src) {
const tokens = lex(src);
const ast = parse(tokens);
// typecheck(ast) skipped to save time
return codegen(ast); // emits ADD for every +
}function compile(src) {
const tokens = lex(src); // throws at line:col on a bad character
const ast = parse(tokens); // throws at line:col on a bad token
const env = {};
for (const st of ast) // throws on int + str
env[st.name] = typecheck(st.e, env);
return codegen(ast); // ADD or CONCAT from the checked type
} Watch PIPELINE DATA. Each row is the real output of one stage. LEX ERROR and PARSE ERROR stop at a line:column before any code exists. TYPECHECK SKIPPED turns the invariant red at codegen and stores 8194. FIX: TYPECHECK FIRST stops the same source at 3:11.
This pipeline stops let z = n + s; at the checker. Inject one fault so that code for the ill-typed program gets emitted anyway.
GOAL: codegen emits code for an ill-typed program
Write typecheck(ast, env). Nodes: {k:'num'}, {k:'str'}, {k:'var', name}, {k:'add', l, r}, {k:'mul', l, r}. env maps names to 'int' or 'str'. Return the expression's type, or throw an Error for: an undefined name, + on mixed types, * on anything but two ints.
Every compiler and many tools that look like one: SQL engines (parse, bind, plan), template engines, config validators. The bug shape is a fast mode that skips a check and lets later stages trust input nobody checked. TypeScript transpile-only builds skip the checker too, but its output does not depend on types, so there the type errors surface at runtime instead of compile time.
“Walk me through what a compiler does with a line of code.” Name the stages and what each hands on, say where each kind of error is caught and why it carries a location, and explain why codegen depends on type information.