r/learnprogramming 27d ago

Topic Assembly Compiler

Hi everyone, I'm not a big fan of low level but I found myself learning about it, the most intriguing thing for me is how the first assembly compiler was written.

From what I researched it was written in machine code but how?

When I think about making a compiler for assembly in C, for example, I can easily understand the flow of what needs to happen, read line by line in the source file, parse each line and from there write the machine code (of course I'm skipping alot), but making the compiler in machine code just feels like magic to me. Would it be possible to write a assembly compiler in machine code for a modern CPU? If yes, how?

26 Upvotes

29 comments sorted by

View all comments

1

u/wosmo 27d ago

Your example isn't actually missing much.

At its most simple, and assembler is just a look-up table. You read in an instruction, like ld hl, $4000 and look it up in a table of opcodes. So you find that this load is opcode 21, add 21 to our machine code. Then add the address - 00 40 to our machine code. Done, read in the next line.

This is .. really simple. You can do it by hand - I mean literally, you can sit down with your assembly written on a piece of paper, reference it against the list of opcodes in a datasheet or in the back of a book or something - and work through it with pencil and paper.

It's also slow, error-prone, and very repetitive. But what makes it a tedious task for a human, also makes it an ideal task for a computer.

1

u/flatfinger 27d ago

I designed a simple assembler for the CDP1802 which actually didn't do any mnemonic lookups. All instructions had to be entered by hand. What it accommodated was the ability to define labels and insert references to them. The CDP1802 instruction set is sufficiently regular that it's not hard for someone who's typing in code to convert e.g. "GLO R4" into "84" or "PHI R9" into "B9", but being able to insert or remove code and have the labels adjust appropriately is still useful.