Orlando, FL
Posts

Building a Compiler from Scratch in C

August 15, 2022
For COP3402 (Systems Software) at UCF, I built a complete compiler for the PL/0 language in C. This post walks through the four-stage pipeline: lexical analysis, parsing, code generation, and virtual machine execution.

Why compilers matter

Every language you write in goes through a compiler or interpreter. Understanding how that pipeline works — how text becomes tokens, tokens become structure, structure becomes instructions, and instructions become execution — changes how you think about the code you write every day. Building one from scratch strips away the abstraction and forces you to deal with the actual mechanics.

The pipeline

The compiler has four stages, each feeding into the next:
Source code → Lexer → Tokens → Parser → Instructions → VM → Output
All four components are written in C with no external libraries. The entire project compiles with a single gcc command.

Stage 1: Lexical analysis

The lexer (lex.c) reads the source file character by character and produces a stream of tokens. Each token has a type (keyword, identifier, number, operator) and a value. The interesting parts:
  • Keyword recognition: 13 reserved words (begin, end, if, then, else, while, do, call, const, var, procedure, read, write) are identified after reading a full identifier, then checked with a chain of string comparisons.
  • Block comments: /* ... */ comments can span multiple lines. The lexer skips the comment body and reports a never-ending comment error when the closing */ is missing.
  • Compound operators: +=, -=, *=, /=, and %= require one character of lookahead. When the lexer sees +, it peeks at the next character. If it's =, it emits a compound assignment token; otherwise, it emits a plain +.
  • Error handling: 5 distinct error types: number too long, identifier too long, invalid symbol, never-ending comment, and invalid identifier.

Stage 2: Recursive descent parsing

The parser (parser.c) consumes the token stream and enforces the PL/0 grammar. It's a recursive descent parser — each grammar rule maps directly to a function. For example, the grammar rule for a statement:
statement := ident ":=" expression
           | "call" ident
           | "begin" statement { ";" statement } "end"
           | "if" condition "then" statement ["else" statement]
           | "while" condition "do" statement
...becomes a statement() function that checks the current token and dispatches to the right branch. If the token is an identifier, parse an assignment. If it's call, parse a procedure call. And so on.

Symbol table and scoping

The parser maintains a symbol table that tracks constants, variables, and procedures. Each entry stores the name, type, lexicographical level (scope depth), and value or address. When the parser encounters an identifier, it looks for a matching entry that is still in scope (entries are marked when their procedure ends) and keeps the one with the highest lexicographical level, so the innermost declaration wins. This lexicographical scoping means a variable declared inside a nested procedure shadows one with the same name in the outer scope — exactly how you'd expect scoping to work. The parser reports 19 distinct error messages, covering cases like: missing semicolons, undeclared variables, assigning to constants, and calling non-procedures.

Stage 3: One-pass code generation

Code generation happens during parsing — not in a separate pass. When the parser recognizes a construct (an assignment, a loop, a procedure call), it immediately emits instructions. The instruction set has 9 opcodes:
OpcodeNameFunction
LITLiteralPush a constant onto the stack
OPROperationArithmetic and relational ops, and procedure return
LODLoadLoad a variable's value onto the stack
STOStorePop the stack into a variable's address
CALCallCall a procedure (create activation record)
INCIncrementAllocate stack space for local variables
JMPJumpUnconditional jump
JPCJump ConditionalJump if top of stack is 0
SYSSystemRead input, write output, or halt

Forward references

One-pass compilation has a tricky problem: when the parser sees a while loop, it needs to emit a JPC instruction to jump past the loop body — but it doesn't know where the body ends yet. The solution: emit the JPC with a placeholder address, continue parsing the body, then backpatch the real address once the body's end is known. Same approach for if-then-else branches.

Stage 4: Stack-based virtual machine

The VM (vm.c) executes the generated instructions. It has:
  • 3000 words of memory — a unified array where the code segment occupies the bottom and the stack grows upward
  • 3 registers — program counter (PC), base pointer (BP), stack pointer (SP)
  • Activation records: each procedure call pushes a frame with a static link (for lexicographical scoping), a dynamic link (caller's BP), and the return address
The fetch-decode-execute cycle is a straightforward loop: read the three fields of the instruction at PC, advance PC by 3, and execute. The OPR instruction alone handles 13 operations (return, negation, addition, subtraction, multiplication, division, modulo, and 6 comparison operators) by switching on the operand field.
This was the most conceptually dense part. The dynamic link points to the caller's base pointer — it's used to restore the stack on return. The static link points to the base pointer of the lexicographically enclosing scope — it's used by LOD and STO to access variables from outer scopes. When a procedure at level 3 accesses a variable declared at level 1, the VM follows the static link chain twice to find the right activation record. This is what makes nested scoping work at runtime.

What I learned

  • Grammar-driven design works. Mapping each grammar rule to a function makes the parser almost self-documenting. When a bug appeared in parsing if-then-else, I could look at the grammar rule and the function side by side to find the mismatch.
  • One-pass compilation trades simplicity for constraints. No optimization passes, no intermediate AST. But for a language as small as PL/0, it's the right tradeoff — the compiler is fast and the code is short.
  • Activation records are the core abstraction of procedure calls. Understanding how the stack frame stores return addresses, links, and local variables made everything else (recursion and nested scoping) click into place.
Source code: github.com/egallardop13/System-Software