November 25, 2026

I wrote an assembler

I wrote an assembler in assembly language, because I had to.

My assembler targets the Intel 8086 microprocessor, which was released in 1978. If humans have a primitive reptilian brain, the 8086 is the primitive reptilian brain of your PC-compatible computer (or your old Intel-based Mac).

The history of the 8086

Intel released the 8086 microprocessor in 1978. It was their first 16-bit microprocessor, following the very successful 8080 and 8085 8-bit microprocessors. To make it easier to port the (back then) enormous library of software that was available for those processors, Intel made the 8086 partially “source compatible” with them: you couldn’t run an 8085 program on an 8086, but you could convert its source code automatically.

(Other manufacturers also made microprocessors that were compatible with the 8080; for example, Zilog with the famous Z80 that powered the Spectrum, the TRS-80, and the whole MSX family.)

When IBM designed the PC in 1980, they chose to use an Intel 8088 microprocessor, which was a cheaper variant of the 8086. The PC was very successful and IBM published all the specifications, so other manufacturers started building “PC-compatible” computers and many software makers published tons of software for the PC and compatibles.

By the time IBM wanted to make the next model, it had to be faster and able to run all the software that worked on the original PC; therefore, the microprocessor had to be compatible. The 8088 and 8086 were too slow, but the newest model, the 80286, was available.

The 286 (as it was commonly called) could run in a mode called “16-bit protected mode” that allowed it to run several programs at the same time and access up to 16 megabytes of RAM. This was a very useful capability, but it was not compatible with the 8086. However, by that time, Intel had changed their approach to backward compatibility, and the 286 started up in a “16-bit real mode” that worked exactly like an 8086, only switching to protected mode when a program asked it to.

So, by never switching to protected mode, a 286 could be used as a faster 8086 and all the existing software ran without changes.

This continued over the years. The next microprocessor, the 386, could run in “32-bit protected mode”, but it also started up in 16-bit real mode, as did its successor (the 486) and the next one (the Pentium) and the next one (the Pentium II) and every processor in this line all the way to the modern Intel Core processors. The only reason you cannot run DOS on modern PCs is that they don’t include a classic BIOS anymore; you could boot an ancient version of DOS on a PC manufactured as recently as two years ago!

(By the way, the “286”, “386”, and “486” are the reason why this line of processors is called “x86”.)

Drawings of several Intel chips: 8080, 8086, 80286, 386, 486The evolution of Intel microprocessors.

8086 assembly

Processors execute machine code, which is a sequence of binary numbers that the processor decodes to know what to do.

In the 8086, instructions can span from 1 byte to 6 bytes (don’t ask me about prefixes!). For example, the 1-byte machine instruction 0xCC tells the 8086 to execute the code routine associated with software interrupt number 3, while the 6-byte machine instruction 0x81 0x80 0x34 0x12 0x78 0x56 tells it to add the value 0x5678 to the 16-bit value in memory addressed by BX+SI+0x1234.

We often say that machine instructions are “low level”: they deal directly with manipulating individual memory locations, changing the values of CPU registers, and other minutiae. Most programmers avoid having to work at this level of detail, so they write programs in “high level” languages like Go or Rust (or, back in the time of the 8086, Pascal or C) and a compiler turns them into machine code.

Sometimes, however, this generated machine code might be a little verbose or inefficient, so programmers who want to have a lot of control write in “assembly language”, which is a low-level language that maps almost directly to machine code.

For example, in 8086 assembly, the machine instruction 0xCC is expressed as INT 3, and the 6-byte instruction from above is expressed as ADD WORD PTR [BX+SI+1234h], 5678h, which looks almost readable to a normal person and is certainly easier to write.

8086 assembly has some 120 instructions, depending on how you count them. There are arithmetic instructions (ADD, SUB, MUL, DIV, etc.), logical instructions (AND, OR, NOT, etc.), flow control instructions (JMP, JZ, JNE, CALL, RET, etc.), data transfer instructions (MOV, PUSH, POP, IN, OUT, etc.), and processor control instructions (HLT, CLI, STD, WAIT, ESC, etc.).

Some of those instructions don’t take arguments, some take one, and some take two. Typically, for instructions that take two arguments, one of them is considered the “source” and the other is the “destination”. In the common “Intel” assembly syntax, the destination argument comes first. (Why? I guess that’s how the coin fell. Other syntaxes have it the other way around.)

The arguments can be numbers, processor registers, or memory addresses. Not all instructions accept all kinds of arguments. For example, the instruction INT can only take a number, the instruction PUSH can take a register or a memory address (but not a number), and the instruction ADD can take a destination register or memory address and a source number, register, or memory address (but not two memory addresses at the same time).

Programs generally don’t execute from start to finish: they call subroutines, they jump to different parts of the code, and they read and write data from memory. All of these operations require memory addresses, and it would be a nightmare if the programmer needed to calculate them by hand and update them whenever they added or removed code. Instead, assemblers let the programmer define “labels”: names that refer to specific positions in the program whose addresses the assembler calculates automatically.

Another common feature that assemblers provide is support for “symbolic constants” and “macros”. The programmer can define a name for a value or fragment of code, and then when the name appears in the program, the assembler substitutes it. For example, the assembly code could include something like DOSCALL EQU INT 21h, and then the assembler would insert INT 21h in place of the word DOSCALL wherever it appears in the program.

Writing my assembler

When I was a kid, I wanted to learn how to program in assembly, but I didn’t have good learning and reference materials, so I had to settle for BASIC (GW-BASIC at first, Turbo BASIC later) and C (I still have my original Turbo C++ 3.0 box). Now I am [mumble] years older and have more experience and the whole Internet at my fingertips, so why not try writing a program in assembly? In fact, why not program an assembler? Better yet: why not program an assembler in assembly as if it were the early 1980s?

I swear that was my thought process.

Writing an assembler is pretty much the same as writing any kind of compiler: you need to do some tokenization, then some parsing, then generate the output machine code. Since assembly is a low-level language, it might mislead you into thinking that it’s simpler than it is. For example, it does have a type system (registers, segments, numbers, addresses, memory sizes) and, remember, you need to resolve labels and macros.

I wrote my assembler in its own dialect of assembly, so I needed to bootstrap it. “Bootstrapping” is a process you follow to bring up a compiler for a language that is written in the same language. You need a compiler to compile your compiler, but if the compiler is written in the compiler’s language… how are you going to compile the compiler? The answer is: you need another compiler.

In my case, I wrote a prototype of my assembler in the Go programming language. Then I wrote my real assembler in assembly and used my prototype to assemble it into a “native” assembler. Finally, I used the native assembler once again to produce the “self-hosted” assembler: an assembler assembled by itself.

A drawing of the different steps of bootstrapping. First, a sheet of paper with a jigsaw puzzle drawn on it and an arrow, labeled “1”, that points to the Go Gopher. From the gopher, another arrow, labeled “2”, leads to a jigsaw puzzle of a gopher. An arrow, labeled “3”, goes from the sheet of paper to this jigsaw puzzle. Out of the jigsaw puzzle, another arrow, labeled “4”, leads to a jigsaw puzzle that matches the one drawn in the sheet of paper.The bootstrapping process. (1) The assembler’s source code (represented by the sheet of paper with the jigsaw puzzle drawn on it) is fed to the assembler written in Go (represented by the gopher), which (2) produces an assembler built from the correct source code but the wrong assembler (represented by the puzzle with the gopher on it.) Then, (3) the assembler’s source code is fed to this new assembler, which produces the assembler built from the correct source code and assembler (4).

A note before we continue

Because it’s the year 2026, I have to say this: I wrote all the code for my assembler myself, but I used an LLM for code reviews and unit tests. This saved me from having to spend a ton of time chasing bugs: the LLM would look at my code and say things like “you used JE when you meant to use JNE” or “you have an off-by-one error here” and I could fix that right away instead of spending hours staring at Turbo Debugger and not seeing that I wrote JZ instead of JC.

The same goes for this blog post: I conceived and wrote it myself, but used an LLM to look for mistakes and fix my grammar. Apparently, even after living in the US for 17 years, I still write like a Spaniard.

Lexical analysis (extracting tokens)

The first stage in a compiler is lexical analysis, which is a fancy name for “extracting the basic elements of the language”. Those elements are symbols (comma, colon, brackets, etc.); keywords for instructions (MOV, ADD), directives (ORG, EQU), registers (AX, CL) and segment registers (ES, SS); numbers (100h, 42); strings ('Hello world'); identifiers for labels; and end-of-line and end-of-file indicators.

As the lexical analyzer (or “lexer” for short) runs, it reads the input file and returns the tokens it detects along the way: the keyword MOV, the register AX, a comma, the number 1234h, an end-of-line, an identifier START, a colon, the keyword CMP, etc.

An illustration of tokenization, shown from the instruction “MOV AX, ES:[BX+20h]”. The “MOV” is marked as an instruction, the “AX” as a register, the “,” as a comma, the “ES” as a segment, the “:” as a colon, the “[” as a left bracket, the “BX” as a register, the “+” as a plus, the “20h” as a number, and the “]” as a right bracket.How a fragment of assembly code is tokenized.

The magic lives in the LEXER_NEXT subroutine: every time it is called, it reads the next token from the source file and places it in memory. It starts by reading single bytes from the source file until it finds a non-whitespace character. Then, depending on the character, it prepares to emit a token of the appropriate type.

Symbol characters (comma, colon, brackets, etc.) are easy: it only needs to emit a token of the corresponding type, like a “colon” token for a colon, a “comma” token for a comma, etc.

Single quotes are for string tokens. The lexer continues reading bytes until it finds the matching single quote, and then it emits a string token.

Number tokens are slightly more complex. They start with a decimal digit and then the lexer reads and parses the number until it has either a complete number (emitting a number token) or an invalid number (which outputs an error message).

Finally, alphabetic characters can be the beginning of a register, segment register, keyword, or identifier token. The lexer keeps reading alphanumeric characters to get the identifier, checks if it’s a known keyword, and emits a token of the appropriate type if so. Otherwise, it checks if it’s a registered macro’s name and expands it; if not, it emits an identifier token.

(In practice, the lexer does not read the source file one byte at a time, because that would be brutal for performance; it reads a big block of data into a buffer, and then it reads individual bytes from that buffer.)

I will explain later how the lexer does macro expansion and include file handling.

Syntactic analysis (parsing) and machine code generation

My assembler is designed to run on a not very fast 8086 with not much memory, so it drives code generation directly from the syntactic analyzer (or “parser”). This was common in assemblers and compilers of that era; nowadays, compilers usually build a syntax tree that they can use for type checking and optimizations and whatever other things modern compilers do.

The parser is implemented as a recursive descent parser. This means that at some point I defined a grammar for the assembly language, and this grammar has “production rules” that are implemented through subroutines that call each other.

For example, there is a rule that says that a “byte element” consists of either a string, a number expression, or a number expression followed by DUP and a byte element in parentheses. In fancy computer science notation, the production rule looks like this:

byte_element ::= string | number_expression | number_expression DUP ( byte_element ) ;

The recursive descent parser for this production is a subroutine named PARSE_BYTE_ELEMENT that checks if the first token is a string; if not, it calls PARSE_NUMBER_EXPRESSION and then checks if the next token is DUP. If it is, then it checks that it is followed by an opening parenthesis, calls PARSE_BYTE_ELEMENT recursively, and finally checks for a closing parenthesis.

As you can see, each production is implemented by a subroutine that calls other parsing functions, recursively if needed. That’s where the “recursive” part comes from. The “descent” part indicates that this is a top-down parser, which goes from the top of the parse tree (the program) to the bottom (the numbers, the strings, the individual symbols).

When some of those parsing subroutines find a match, they emit some machine code or data corresponding to the language constructs they parsed. For example, if the PARSE_BYTE_ELEMENT subroutine finds a string, it emits the content of the string; if it finds a single number expression, it emits that number as a byte; and if it finds a number expression followed by DUP and a byte element, it calls the function recursively several times.

Emitting machine code

The assembler’s grammar has an “instruction” production rule. When its PARSE_INSTRUCTION subroutine finds a match, it emits the corresponding machine code.

An assembly instruction can be encoded as a machine instruction in many different ways. Some instructions have only one form, like CLI or HLT, which are encoded as a single byte. Other instructions can be encoded in several different ways depending on their arguments (MOV has 26 different encodings!). What’s more, some instructions, like ADD AX, BX, can even be encoded in two different ways for the exact same arguments.

To handle this, the production rule parses any instruction with any combination of zero, one, or two arguments of any type, and then it uses a table to look up the appropriate encoding for the given instruction and arguments.

To build the table, I classified all the possible instruction encodings into 15 different patterns and then assigned an encoding pattern to each instruction. If the arguments match one of the possible encodings for that pattern, the corresponding machine code is emitted; if not, the assembler displays an error message.

(For the cases where the same arguments can result in two encodings, I chose the shortest one when possible; other than that, my choice was arbitrary.)

Labels

Labels stand for memory addresses. You can specify a label before a machine instruction or a data definition, and wherever it appears, the assembler replaces it with its address.

A piece of assembly code on the left, and with addresses assigned to each instruction on the right. There is a “LOOP” instruction that points to a label on the left and to an address on the right.As the assembler parses and generates code, it keeps track of the current memory address. Wherever a label is defined, the assembler stores the label’s address; wherever a label is used, the assembler replaces the label with its address.

Crucially, you can use labels before they are defined (and they still work correctly). There are two ways to achieve this. The fancy way is to use placeholder values wherever there is a reference to a label that hasn’t been defined yet, and then go back and rewrite (“backpatch”) those placeholders with the correct value. The mundane way, which my assembler uses, is to assemble the program twice: the first time to build the symbol table with all the label addresses filled in, and the second time to emit the code.

This makes my assembler a “two-pass” assembler, because it runs through the source code twice. An assembler that reads the source code only once is a “one-pass” assembler. One-pass assemblers are generally faster, but they require more memory and are more difficult to program. Two-pass assemblers were common in the 8086 era, so I followed this model to be more authentic (and, I’m not going to lie, because it’s easier).

Short jumps

The 8086 has lots of jump instructions. There is the regular unconditional jump instruction (JMP), a subroutine call instruction (CALL), some instructions for loops (LOOP, LOOPZ, LOOPNZ, JCXZ), and dozens of conditional jump instructions (JE, JC, JO, JPE, JNZ, etc.).

All of those instructions use “relative addressing” to specify the destination address as an immediate value. What that means is that, if address 100h contains a JMP 120h instruction, it is not encoded as “jump to address 120h”, but as “jump 20h bytes ahead” (not exactly, but I’ll satisfy the pedants later). The same goes for CALL, LOOP, and all the conditional jump instructions.

Jump instructions use relative addressing to make it possible to write position-independent code. Some programs include snippets of machine code whose memory location is not known beforehand, so they need to be able to run wherever they happen to be. Thanks to relative addressing, all the jump instructions will work correctly without having to rewrite them or anything.

Relative addressing also allows for a (small) optimization: most jumps occur within a very short distance of the jump instruction, so if the distance is small, it can be encoded in one byte instead of two. This was very important when memory was scarce and expensive (you may think that it is scarce and expensive now, but that is nothing compared to when it was sold by the kilobyte).

Jumps whose distance fits in one byte are called “short jumps”. Unexpectedly, jumps with a two-byte distance are not “long jumps” but “near jumps” to distinguish them from “far jumps”, which jump to a different code segment. (I’ve mentioned segments in this blog, but I’m not going to explain them because I want to finish writing it this year.)

Conditional jumps are always short, and the assembler shows an error message if the target of the jump is not reachable via a short jump.

The JMP instruction can be short, and the assembler can detect it automatically for backward jumps, but not for forward jumps (because in a forward jump, the label is undefined when it appears in the JMP instruction so the assembler can’t know if it’s near or short). You can use JMP SHORT to force it, and then the assembler will give an error if it’s not possible.

Note to satisfy the pedants: the jump address is relative to the address of the instruction that follows the jump instruction, not to the address of the jump instruction itself, so the JMP 120h instruction from before would have been encoded as “jump 1Eh bytes ahead”, not “jump 20h bytes”. The reason is that, when the instruction is being executed, the instruction pointer register (IP) already points to the next instruction, so the jump displacement has to be relative to that.

Symbolic constant (EQU) support

My assembler has support for symbolic constants, and I think I was slightly cheeky when I implemented it, because it can be used to replace any sequence of tokens, not just constants or expressions.

The lexer has a “macro expansion mode”. When it’s enabled, the lexer returns tokens from a list in memory, not from the source file. When the list ends, the lexer exits macro expansion mode and resumes reading the source file.

When the parser detects an identifier followed by EQU, it reads all the following tokens up to the end of the line and stores them in an entry in the “macro map” (indexed by the identifier).

When the lexer detects an identifier, it checks if it appears in the macro map. If not, it returns a token for the identifier; otherwise, it enters macro expansion mode to return the tokens from the identifier’s entry in the macro map.

Include files

The assembler also supports “include files”, which makes it possible to reference other files to be parsed as if they had been inserted in the original file.

When the parser detects the keyword INCLUDE followed by a file name, it opens that file and tells the lexer to include it. Then, the lexer pushes its current state onto a stack and prepares to read from the include file instead of the original file.

When the include file ends, the lexer does not return an end-of-file token. Instead, it pops the previous state off the stack and resumes reading from the original file.

Thanks to the stack, nested includes are possible: a file can include another file that includes another file, and so on.

Performance

My assembler can assemble itself at 75 lines per second on an IBM PC/XT (measured on a cycle-accurate emulator). This is twice as fast as Microsoft Macro Assembler 4.0, but only half as fast as Turbo Assembler 1.0 (though TASM is a one-pass assembler, so it makes perfect sense). I’m pretty happy with that speed, and it did take some engineering to achieve it.

The label and macro maps

The assembler spends a lot of time looking up label and macro definitions. To make those as fast as possible, I implemented hash tables in assembly.

(If you are the person who recently commented on Hacker News something like “I didn’t know it was possible to write a hash map in C”, prepare to be astounded.)

There are two tables: one for the labels, and one for the macros. Each table has a fixed 256 buckets, and each bucket contains a linked list: the first 256 words in each segment are pointers to the first element of each list, and then each element is prefixed by a pointer to the next element.

Illustration of the hash tables. Each bucket (numbered from 0 to 255) has a pointer. Some pointers are null and lead nowhere. Other pointers lead to an element, which consists of a pointer and some content. The pointer leads to the next element of the list, or null if there are no more.

I used a Pearson hash function, which is slightly anachronistic (invented in 1990) but very fast (it is almost like the 8086 was built for it). The hash table does not run in O(1) time because it has a fixed number of buckets (and a pretty small number at that), but with 256 buckets, it’s going to be 256 times as fast on average as a straight array search, so it is certainly worth the effort.

When I add elements to a list, I append them to the end. You might think that I could have inserted them at the beginning and avoided the full list traversal, but that’s not right: I need to check for duplicates, so I would have needed to traverse the list anyway. I haven’t tested if recently added elements are more likely to be accessed, which would benefit from inserting at the beginning. I suspect that macros might benefit, but labels wouldn’t because of the two passes.

Keyword lookups

Another spot where the assembler spends a lot of time is looking up keywords. Every time the lexer detects an identifier, it needs to check if it’s the name of a register, a segment register, or a keyword (directive or instruction). My original code just went through a list and checked if the identifier matched one of the entries. My current code is a little smarter.

First, it checks if the identifier has length 2. If not, it can’t be a register or segment, so the lexer can skip those checks. All other keywords have lengths between 2 and 7, so it only checks if the identifier is in that range.

Registers and segments are checked in code, using a tree of comparisons and conditional jumps. All segment names end in “S”, so if the identifier’s second character is not that, it can’t be a segment. Otherwise, the first character must be “E”, “D”, “C”, or “S”. For registers, if the identifier ends in “X”, “L”, or “H”, it must start with “A”, “B”, “C”, or “D”; if it ends in “I” it must start with “S” or “D”; and if it ends in “P” it must start with “S” or “B”.

For keywords, the code still uses the list, but it tries to be clever about it. All keywords are 2 characters or longer, and all strings in my program are prefixed with the length, so it is possible to compare the length and first character of each keyword at the same time with the CMPSW instruction. If they don’t match, the program can skip directly to the next word.

Other small and micro-optimizations

I performed a lot of small and micro-optimizations along the “hot path” of my assembler. Cycle counting is accurate in the 8086, and my LLM knows a lot about it, so it could suggest some optimizations and then I could run away with them and make them even better.

I got a lot of mileage out of avoiding jumps within the most common code path: a jump taken takes about 12 cycles longer than a jump not taken, so being mindful of that can make the code very fast.

Something I did from the beginning was tail-call optimization: whenever I needed to call a subroutine at the end of another subroutine, I would just JMP into it instead of doing a CALL followed by a RET. This saved one instruction and two stack accesses per call. I even managed to optimize PARSE_BYTE_ELEMENT and turn it into an iterative function!

Code size and memory usage

In the end, the assembler has about 10 kilobytes of machine code. I managed to bump all the buffers and scratch space (some 3.5 kilobytes) into uninitialized data at the end of the program so it doesn’t occupy space in the file. The stack grows downward from the end of the code segment. I also used two more segments for the labels and macros hash tables, respectively.

A map of the memory used by my assembler, as explained above.

This brings the total memory usage to 192 kilobytes which, compared to an assembler from that time, is probably quite profligate if not downright wasteful.

There is an easy opportunity to save memory. Thanks to my use of tail-call optimization, there are no mutually recursive subroutines in the program, so the CPU stack never goes deeper than 80 bytes. If I limited the “include” stack to 3 levels, I would be able to move the CPU stack down and shrink the program segment to 15 kilobytes, saving 49 kilobytes! I’ll do it if I revisit this project in the future.

Conclusion (why I did it)

As I wrote above, this is the year 2026, and LLMs have made it very weird for those of us who write programs. I just emerged from a year of mourning for my profession and my hobby while I tried to figure out what was going to become of them.

I thought of the many professions that were upended by automation, by power tools, or by “better” ways to do it. In the end, I likened myself to an artisan woodworker who can design and build spectacular masterpieces of furniture but must live in a place and time where most people are only willing to pay flat-pack prices for flat-pack quality.

So, if jobs are now about cutting boards for flat-pack furniture on the table saw, we’ll cut boards for flat-pack furniture on the table saw. And if we have to live in the same world as people who buy cheap flat-pack at the discount store and call it “IKEA”, we’ll do it.

And those of us who can build a wooden coffee table with nice carvings and volutes and fancy turned legs and inlays and all that special stuff… maybe we’ll build one of those every once in a while to keep our skills sharp while we hope that someone will come along who will appreciate it and maybe even buy it.

There’s a debate on whether programming is art. I think it is. Or at least, that’s what I was trying to do when I built this assembler. I had a story in my head about a Spanish software company from the early 1980s that would have written and published it, and as I designed and wrote my program, I kept asking myself, “Would they have done this? Would they have done it this way?” I was trying to build my program into a story, or maybe build a story into my program.

Nobody needs a new 8086 assembler in the year 2026. For sure, I did not need a new 8086 assembler in the year 2026. But I needed to write a new 8086 assembler in the year 2026. Maybe, in the end, that’s what art is.

Except where indicated otherwise, this page and its contents are Copyright © Jacobo Tarrío Barreiro. All Rights Reserved. Privacy statement and terms of use.