'Is it practical for a Forth implementation to use the system stack as the return stack?
A language like C uses the system stack for local variables and return addresses. Forth has the data stack and the return stack. Is there an implementation of Forth that uses the system stack as the return stack and hence uses the return instruction to end execution of a word? Is this a feasible approach?
Solution 1:[1]
The native call
and ret
instructions are used in the subroutine-threaded code. And in this case the system stack plays role of the return stack in Forth.
SP-Forth/4 is an example of a Forth system that uses this approach (see forthproc) along with peephole optimization.
Solution 2:[2]
Yep, it's perfectly feasible.
It is probably only useful if you compile words instead of interpreting them, and you'd need to write some kind of stack frame convention if you want to catch return stack errors instead of just crashing.
Solution 3:[3]
It's possible to make a Forth-like language that uses only one stack, but if you want a Forth that's compatible with standard Forth programs you would need separate data stack and return stack. Forth passes arguments from function to function by just leaving them on the data stack; if you use one stack for both data and flow control you need to be careful to clean the data off the stack before a function ends.
Solution 4:[4]
There are computers where every register is usable as a stack pointer. A return stack is where you push return addresses when you perform a call, at least assuming that instruction is available.
There are different Forth implementation paradigms, native code and threaded code. That means that you normally reserve two registers for the Forth data stack and the Forth return stack. In native code it makes more sense to use the processor return stack as the Forth return stack, where you generate call and return instructions. In threaded code you can select the return stack for the Forth data stack in order to take advantage of special push and pop instructions for speed and compactness and you must select another register for the Forth return stack pointer.
Bottom line is that normal users of Forth don't notice it. If you are implementing a Forth you probably take many more circumstances into account, in particular what role the return stack plays in interfacing with the operating system.The bottom line is that it is a design decision and not particularly notable by the Forth user.
This comment is a little bit geared towards ARM and AMD86 processors. For an 1802 processor e.g. the question hardly makes sense.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ruvim |
Solution 2 | Useless |
Solution 3 | steveha |
Solution 4 | Albert van der Horst |