3 ms·
Forth can be interpreted but it can also be compiled in at least two or three different ways. Forth is unique in that its interpreter can look (and perform) a l
by dreamcompiler 4y ago
Forth can be interpreted but it can also be compiled in at least two or three different ways. Forth is unique in that its interpreter can look (and perform) a lot like compiled code.
Let's say you have a list of assembly language function names FOO, BAR, BAZ, etc. Each name stands for the starting memory address of that function. Each function ends with a standard RET instruction. At address PROGRAM, you store the list of 64-bit function addresses. Now a "Forth Interpreter" is just
JSR-INDIRECT RP++
REPEAT
where beforehand you've stashed PROGRAM in register RP. Most assemblers don't provide an indirect JSR instruction but it's easy to write a macro that serves that purpose.
Is this an interpreter? The only way it differs from true compiled code is that the function calls are indirect, so it's almost as fast as regular function calls.
What if you unroll the thing so the code looks like
JSR FOO
JSR BAR
JSR BAZ
...
Now all the function calls are direct. And as a bonus, all the individual functions themselves don't have to do anything more special than directly call functions. It's turtles all the way down.
I've glossed over some issues like how to pass values and how many stacks you need and proactive tail-calling, but that's the gist of it. The whole "interpreter" just vanishes in a puff of smoke.
- terminalcommand 4y agoThank you, I didn't know about the jsr instruction. I always imagined forth does this somehow with jmps. Another main difference from true compiled code is that your entire program consists of subroutine calls. There are no inline instructions and a main function. I've got a lot of reading to do on this. "Indirect jsr", I'll experiment with this. Okay I'm convinced, forth is not interpreted when it's compiled to threaded code :). There is no main loop that reads instructions and dispatches them dynamically, the program flow is linear with subroutine calls stacked under each other.
- dreamcompiler 4y agoExactly. And there are many other inline instructions (e.g. for doing arithmetic etc) but I didn't show them here. Any instruction the CPU supports can be present in a Forth program. In a compiled Forth, words can be specified as a list of calls to other Forth words or as raw assembly instructions, or both.
- terminalcommand 4y agoThank you for the explanation. Wow, these were questions stuck in my mind for a long time. Things make sense now.