Show HN: CPU simulator in 60 lines of code
github.com
github.com
My mind was absolutely blown when I first realized that the function of a CPU is pretty much to read tokens from a stream and perform an action for each. - no magic!
Your instruction look up becomes your execution step in one go: https://github.com/jarcane/MicroMini/blob/master/main.rkt
The magic is mostly in the pipelining bit :)
My "aha!" moment when I first learned about CPUs was the program counter, or if you're an Intel guy, you'd call it the instruction pointer.
The PC might seem obvious, but if you think about it for a moment, you'll realize that someone had to have invented it. It's not totally obvious. And as far as I can tell, the inventor is unknown.
Note also that the featured program does not have a PC, so there are things it can't do that a normal CPU can do.
Having RAM seems to be important to having a PC, that works well.
However I fixed the issue and gave you the credit:
https://github.com/wkoszek/cpu60/commit/672711f3e06bba424b98...
https://github.com/kragen/calculusvaporis/blob/master/cavosi... is a CPU simulator in 70 lines of code, but it's perhaps a bit impractical; you have to synthesize addition from subtraction, for example, and AND and OR from NAND. The design objective of Calculus Vaporis, however, is to use as few logic gates as possible, rather than to be as simple as possible in C.
http://canonical.org/~kragen/sw/aspmisc/brainfuck.c is a 66-line BF interpreter, but BF is not a very good CPU design, in that it doesn't support subroutines.
I see no claim for it to be?
Personally, my inclination would be to rewrite the loop to tighten it up. But maybe the point was to show how quickly and dirtily one can do this... it definitely looks quick and dirty.