3 ms·
I wrote a stack based language for the 6502 before. It's actually really trivial to do. If you have stack code that looks like this: "foo bar qux baz" and want
by pubby 8y ago
I wrote a stack based language for the 6502 before. It's actually really trivial to do.
If you have stack code that looks like this: "foo bar qux baz" and want to convert it to assembly, all you have to do is insert JSR instructions between the words:
JSR foo
JSR bar
JSR qux
JSR baz
To define subroutines, insert a label and an RTS function around code blocks. For example, to define a subroutine called qux using the code ": qux foo bar", the output would be:
qux:
JSR foo
JSR bar
RTS
The last thing needed is the ability to push literals onto the stack. In my language I defined literals as things between parenthesis. I compiled them by outputting a PUSH_LITERAL assembly macro. Code like "foo (5) (6) bar" would be compiled as:
JSR foo
PUSH_LITERAL 5
PUSH_LITERAL 6
JSR bar
That's it! You could implement an entire compiler in 50 lines of code. (of course, writing a proper FORTH requires more than this toy example)