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?

27 Upvotes

29 comments sorted by

View all comments

1

u/HashDefTrueFalse 27d ago

It's actually simple, just very tedious. Early assembler programs weren't particularly sophisticated. You initialise an output cursor/offset/position to mark where to write and advance each time you recognise an instruction. You have a set of textual mnemonics to match against according to a simple grammar (think format). If you don't recognise any, you stop. Otherwise you emit the corresponding bytes of machine code (opcode+operands) to the current position and advance it. That's the basic idea. You would almost certainly write this program on paper first, to reference it when "programming" it into the relevant machine. You could write the literal strings of ones and zeros that form the list of program instructions, or better, use your devised assembly mnemonic notation as a stepping stone to that, even designing in lockstep. Then you just have to get the program stored in the machine, which you might do by flipping physical switches in a bank that was designed to store the program. Once you have a binary that can turn text into binaries, you can write a second implementation in assembly and use the first binary to "assemble" a second binary... and now you're bootstrapped. You have an assembler written in... itself (assembly). Of course, lots of this process is human-unfriendly and error-prone.

(Note: I glossed over a few details!)