One day on IfNotNil we were discussing byte code and interpreters.
And the conversation came around to old CPU’s like the 6502. One many folks cut their teeth on. My first computer was a TRS-80 CoCo and after than I stepped up to an IBM clone; a TI Professional which lasted me through University and up until I started my first job after school.
As part of the discussion it was hinted that writing a byte code interpreter for any one of several old 8 bit CPU’s might be an interesting diversion. And it might also prove to be useful as a learning exercise for others.
Since the 6502 is an 8 bit only machine it basically is a “byte code” interpreter by its very definition. Each opcode is entirely contained in one byte – instead of like some current machines today that have very wide opcodes.
As such its possible to encode EVERY opcode and an associated handler in a simple table of 255 entries that, when an opcode is encountered, the handler is fetched from a table of handlers and invoked.
Those handlers are all 0 parameter methods that fetches whatever necessary operands it requires, executes the specific instruction, sets registers, and returns.