How it works
I wrote this compiler in 2006 as an exam project: a compiler for a small Pascal-like language, written entirely in 8086 assembly, that writes 8086 assembly for MASM. In 2026 I found the archive and got it running again, in DOS and in the browser. This page explains how it works, with the real code.
The 2006 project
The goals, as I listed them on the first slide:
- Translate programs in a pseudo-Pascal language into assembly that MASM and LINK accept, and that works.
- Integer and character variables, one-dimensional arrays, and string constants, enough to give the programs a minimal interface.
- IF-ELSE, WHILE and LOOP, and arithmetic and boolean expressions with the right operator precedence.
- Built-in procedures for keyboard and screen I/O.
- Proper error handling: show the line and the kind of error.
The compiler is about 2,700 lines of 8086 assembly in ten files, plus a small runtime library. The two
I/O libraries it used then, which I didn't write (GIOBE, from Giorgio Ober's assembly tutorial, and
UTIL_PRG), are replaced by RUNTIME.ASM in this version. The character and string routines come from the UCR
Standard Library that goes with Randy Hyde's The Art of Assembly Language, and I wrote the file
I/O from scratch on DOS INT 21h, with 256-byte buffers so the scanner can read the source
one character at a time.
The 2006 slides (PDF, Italian)
The books and sites in the bibliography were:
- Jack W. Crenshaw, Let's Build a Compiler
- Randy Hyde, The Art of Assembly Language, and the UCR Standard Library
- Aho, Sethi and Ullman, Compilers: Principles, Techniques, and Tools
From Pascal to assembly
The folders in the archive show the order I built it in:
- cradle and tiny: Crenshaw's tutorial, worked through in Turbo Pascal. Like the tutorial, they compile expressions and then a tiny language to Motorola 68000 assembly.
- 80x86: the same compiler in Turbo Pascal, retargeted to Intel 8086 and MASM, with the whole language: arrays, strings, LOOP, READINT, inline MASM. It's in the repository as
prototype/80X86.PAS. - The assembly version: the Pascal compiler rewritten by hand in 8086 assembly, procedure by procedure. The names stayed the same:
Expressionin Pascal becamepExpressionin assembly.
The Pascal version was the specification. Each Pascal procedure is a few lines; in assembly the same
procedure needs explicit registers, a stack for anything recursive, and strings handled one byte at a
time. Recursion is what makes it hard: pExpression calls pTerm, which calls
pFactor, which can call pBoolExpression again for a parenthesis, and every
level has to keep its own state somewhere.
The language
To keep the compiler simple, every construct has its own closing keyword (endif,
endwhile, endloop), = is both assignment and comparison, case
doesn't matter, and ; starts a comment. Integers and characters are the same 16-bit type;
only the I/O procedures differ.
program
var a, b, i ; 16-bit signed integers (also used as characters)
array v[10] ; arrays of integers, indexed from 0
$hello = "Hello!" ; string constants, for writeStr
begin
a = 7 * (b + 1) / 2 ; + - * / and parentheses
if a > 3 & !(b = 0) ; = <> < > <= >= & | ~(xor) !(not)
writeStr($hello)
else
writeInt(a)
endif
while i < 10
v[i] = i * i
i = i + 1
endwhile
loop 3 ; repeats 3 times, with the 8086 LOOP instruction
write('*')
endloop
read(a) ; a key, without echo
readInt(b) ; a number, with echo
write(a) ; a character
newline
masm ; assembly, copied to the output as is
mov ax, a
shl ax, 1
mov b, ax
endmasm
end.
Lexical analysis
The scanner (the lexer) reads the source one character at a time into Look, a single
character of lookahead. pNext skips white space and comments, looks at the next character
to decide what kind of token starts there, and reads the whole token: an identifier, an integer literal,
a character literal like 'a', a string constant identifier like $hello, or an
operator. It leaves the lexeme, the token's text, in Value and the token type, a single
letter, in Token.
Every operator is a one-character token: <= reaches the parser as <
followed by =, and the parser puts the two together. Keywords aren't recognised by the
lexer either. Where a statement or a declaration can start, the parser calls pScan, which
looks the identifier up in the table of reserved words and replaces the token type x with
the keyword's letter. Inside an expression nobody calls it, and every word is an identifier.
The symbol table
Declarations come first, between program and begin. Each one adds an entry
to the symbol table, a fixed array of 100 entries of 16 bytes, and writes the storage for it into the
data segment of the output (NAME dw 0, NAME dw 10 dup(0), or
$NAME db "text",0). Identifiers are significant up to 15 characters.
The table is only used for two semantic checks: a declared name can't be declared again, and a name used in a statement must have been declared. There are no types to check. Every variable is a 16-bit word, and the table doesn't stop you using an array as a scalar.
Parsing
The parser is a predictive recursive descent parser: one procedure for each nonterminal of the grammar, calling each other the way the productions refer to each other, and choosing what to parse next from the current token, without backtracking. There is no abstract syntax tree and no intermediate representation. Each procedure emits its assembly as soon as it has recognised its part of the input, which is syntax-directed translation in one pass.
<bool_expr> ::= <bool_term> (('|' | '~') <bool_term>)*
<bool_term> ::= <not_factor> ('&' <not_factor>)*
<not_factor> ::= ['!'] <relation>
<relation> ::= <expression> [<relop> <expression>]
<expression> ::= [<addop>] <term> (<addop> <term>)*
<term> ::= <factor> (<mulop> <factor>)*
<factor> ::= <number> | 'c' | <variable> | <array> '[' <bool_expr> ']'
| '(' <bool_expr> ')'
The grammar has one nonterminal per precedence level, so precedence comes from the nesting:
* binds tighter than + because pExpression calls
pTerm for its operands. The repetitions in the productions are loops in the code, which
makes the binary operators left-associative. Here is pExpression, for + and
-:
Code generation
The code generator treats the 8086 as an accumulator machine with a stack. AX is the
accumulator and holds the value of the expression being evaluated. Before the right operand of a binary
operator is evaluated, PUSH AX saves the left one on the hardware stack, and the operator
ends with POP BX and an instruction that combines the two. There is no register allocation
and no optimisation pass, so the code is slow, but it's correct for expressions of any depth and the
code generator stays tiny.
Type an assignment and step through what it compiles to:
Subtraction and division need the operands the other way round: SUB AX,BX computes
right minus left, so a NEG AX follows, and division swaps the registers with
XCHG first.
Relational operators are where the 8086 shows its age. It has no instruction that turns the flags of a
comparison into a 0 or 1, so the generated code calls small routines in the runtime library,
SETE, SETL and the others in RUNTIME.ASM, that leave 1 or 0 in
AX. Boolean expressions are then evaluated in full, without short-circuiting:
&, | and ! are plain AND, OR
and NOT on those values, and a condition only has to test bit 0.
A semantic stack
Each procedure of a recursive descent parser needs its own copy of some values while the procedures it
calls run. When pFactor sees an identifier, it can't emit MOV AX, name yet:
it has to read the next token to see whether a [ follows and the identifier is an array.
Reading the next token overwrites Value, and the index expression inside the brackets can
contain more identifiers, each read into Value again.
In Pascal a local variable does it. In assembly I wrote PushString and
PopString, which keep whole strings on the 8086 stack: in compiler terms, a small semantic
stack for the attributes (names and labels) a procedure needs after the ones it called have returned. The catch is that the procedure's
own return address is on top of the stack, so PushString pops it first, pushes the string
one character per word, and puts the return address back on top before returning:
The labels of nested IF and WHILE statements go through the same stack. The compiler's stack segment is 1 KB for that reason, where the programs it compiles get 256 bytes.
Control flow
A WHILE needs two labels: one at the test, to jump back to, and one after the loop, to leave. The
compiler makes up both names before it parses the loop, and the assembler resolves the forward
reference to the second one, so the compiler never has to go back and patch a jump address
(backpatching). The 8086's conditional jumps only reach 128 bytes either way, and a loop body is
usually longer, so the condition jumps over a JMP that can go anywhere:
while i < 10
i = i + 1
endwhile
This is the procedure that writes it. Each call to a w... procedure writes a piece of the output:
What it can't do
The last slide listed the limits. Floating point would have meant doubling every integer routine.
Arrays have one dimension. The hardest one to fix was procedures and functions: they need local and
global variables, parameters passed by value and by reference, and memory allocated on the stack for
recursive calls, which would have changed the core of the compiler. Programs can still use inline
assembly, masm ... endmasm, for anything the language lacks, as the
guessing game example does to read the BIOS clock.
Two more, in compiler terms: there is no type checking, and there is no error recovery. The compiler reports the first error, with its line, and stops.
The 2026 restoration
The archive had the sources, the 2006 MAIN.EXE, copies of MASM and LINK, and several
backup folders. The first surprise was that the 2006
MAIN.EXE doesn't work in DOSBox either: it can't open its input file. These are the bugs that were
fixed:
ReadString, which reads the file name, had noRET: it ran on into whatever code came next in memory.- After creating the output file, the compiler opened it again, passing the file handle where DOS expects an access mode. DOS refused, and the compiler stopped.
- The symbol table was declared as 100 bytes instead of 100 entries of 16 bytes, so new names overwrote the variables after it.
- Labels were
Lfollowed by one character,'0'+ the count, so the eleventh label wasL:. if ... else ... endifwrote the end label twice. None of the 2006 test programs usedelse.a - b + canda / b * cstopped parsing after the first-or/.!was parsed, but the instruction was never written.writeStr($a, $b)failed at the comma.- Comparisons used the unsigned jumps and numbers printed unsigned, so sorting put
-3after12, as65533. - At the end of the file, the scanner kept reading the old contents of its buffer.
The rest of the work: building with JWasm instead of MASM (it needs -Zm, MASM 5.1 mode,
for the 2006 code), the file name on the command line, English comments and messages, and
RUNTIME.ASM in place of the two libraries I didn't write. The whole toolchain still runs
inside DOS: BUILD builds the compiler, PAS FIBO compiles, assembles and runs
a program.
The browser version
The compiler is ported to TypeScript, one method per assembly procedure, keeping the names, and an 8086 simulator runs the assembly it produces. The simulator reads MASM source, not machine code, and implements the registers, all the flags, segments, the stack, and the parts of DOS and the BIOS that small programs use.
A port is only useful if it behaves like the original, so the tests compare it with the real thing:
A script runs the original compiler in a headless DOSBox on every example and test program, including
the ones with errors, and records the .ASM it writes and its last screen. When a program has
a file of test keys, the script also assembles it, runs it, types the keys and records the screen it
ends on. The tests check the TypeScript compiler against the first recording, byte for byte. They check
the simulator against the second: given the same keys, it has to end on the same screen as DOSBox.
The source is on GitHub, with instructions for running the original in DOSBox.