Forth: A Sojourn Into Stack Comments
This is the first in a series of Forth articles that I’m planning to write (as/when I have the time and inclination) on Forth programming.
This first article isn’t that interesting as it’s only talking about comments – however, comments, and stack comments/stack signatures in particular are essential to writing clear Forth code, so it’s worth learning the best practices up front.
So… stack comments in Forth. They are essential to making your code more understandable for others, and making it easier to re-use code later on. Here’s what a stack comment looks like for a word (Forth parlance for a function or subroutine) that multiplies a value on the top of the stack by 2:
( n – n*2 )
The opening bracket/parenthesis “starts” the comment (the equivalent of REM). Again a space is required after the bracket. Next we see “n”. This is simply a symbolic representation of a number. Note that it is on the left hand side of that – symbol. That symbol separates inputs from outputs. The stuff on the left side are the inputs and the outputs are on the right side. So, this comment tells us that this word expects one number on the stack, and its output will be the same number multiplied by two. How simple is that?
Here’s a stack signature for a multiply word:
( a b – product )
Here, this word takes two inputs from the stack. A and B. Note that B is on the top of the stack (the rightmost value is always the top of the stack) and A is “underneath it” on the stack. So, that’s the “inputs” dealt with. We can see that it produces one output called “product”. Note, that a and b are missing on the output side. This is crucial. It means that the word CONSUMES the A and B inputs (removed them from the stack) when it executes.
Here’s the stack signature for SWAP:
( a b – b a )
So, before execution, two values should be on the stack, b (at the top) and a underneath it, and after execution, a will be on the top (it’s the furthest to the right) and b will be underneath it).
Here’s DUP, which duplicates the topmost stack item:
( n – n n )
You can probably follow that one easily enough.
Here’s the stack signature for a division word:
( quotient divisor – dividend remainder )
So, this word expects two numbers on the stack. The quotient, and divisor (which is at the top). After execution, the quotient and divisor have consumed, and the dividend and remainder will be pushed to the stack.
Note the closing parenthesis which closes the comment. Anything after this will be seen as code that your Forth system should interpret in some way.
Okay, that’s a brief tour of stack comments. As mentioned, they are not essential, but they do make life easier when you come back to your code months later (or look at somebody else’s code).
In the next article, we’ll actually write some code...