by bxparks · 1y ago · 0 comments
I've been reading about Forth for 30-40 years. The dual stack is easy to understand. My problem is that I cannot see how control flow works in Forth, e.g. a simple if-then-else.
I think that something as fundamental as an if-then-else should be obvious in a useful language. Heck, it's obvious in assembly language. But not in Forth.
if (siz != 0) *d = '\0';
is (untested) siz @ 0<> if 0 d @ c! then
when what you'd normally expect is something like if siz @ 0<> then 0 d @ c! fi
but that's sort of a question of RPN. At least else comes where you expect it, even though that makes then even stranger; we can translate if (key < tree->key) {
tree++;
} else {
tree = tree->right;
}
literally as (untested) key @ tree ->key @ <
if kvpairsize tree +!
else tree ->right @ tree !
then
Now, if you were comparing Forth to Lua or C here, I would agree: this is far less obvious, in the sense that it's completely unfamiliar and requires you to learn Forth's idiosyncratic way of writing things. But in assembly language? GCC generates, in context, the following assembly code for the C if-else statement above: addhi r0, r0, #8
bhi .L5
ldr r0, [r0, #4]
b .L6
This is using the flags from a preceding equality comparison, and the branch target labels are earlier in the enclosing loop. You can not tell me that this is "obvious" if you don't know ARM assembly!From a certain point of view, Forth is just what you get if you take assembly language and look for the simplest way to add properly nesting expressions, properly nesting control structures, subroutines with arguments and return values, arbitrary compile-time computation, an interactive debugging environment, a scripting language, disk storage, and multithreading.
What made it click for me was http://www.exemark.com/FORTH/eForthOverviewv5.pdf, specifically sections 2.3 "Loops and Branches" and 5.3 "Structures". With a slight simplification, if/else/then branching is defined in 7 words.
Two primitive words, branch and ?branch (in python because I know it better than assembly):
def branch():
""" branch is followed by an address, which it unconditionally jumps to."""
ip = code[ip] # Get address from next cell in code, jump to it.
def branch_if_zero():
""" ?branch is followed by an address. ?branch either jumps to that address,
or skips over the address & continues executing, depending on the value on the
stack."""
if stack.pop() == 0: # Pop flag off stack
ip = code[ip] # Branch to address held in cell after ?branch
else:
ip += 1 # Don't branch, skip over address & keep executing
Two helper words for forward branching. >MARK adds a placeholder branch address to code and pushes the address of the placeholder. >RESOLVE resolves the branch by replacing the placeholder with the address from the stack. : >MARK ( -- A ) HERE 0 , ;
: >RESOLVE ( A -- ) HERE SWAP ! ;
And then the actual IF, ELSE, and THEN words. IF puts ?branch and a placeholder address in code. ELSE puts branch and a placeholder address in code, then updates the preceding branch address (from an IF or ELSE) to land after the ELSE. THEN updates the preceding branch address to land after the THEN. : IF ( -- A ) COMPILE ?branch >MARK ; IMMEDIATE
: ELSE ( A -- A ) COMPILE branch >MARK SWAP >RESOLVE ; IMMEDIATE
: THEN ( A -- ) >RESOLVE ; IMMEDIATEHopefully this is helpful: https://www.forth.com/starting-forth/4-conditional-if-then-s...
My mental model of Forth is that there is a simple parser that consumes space-delimited keywords. The interpreter looks up that keyword in a dictionary, which gives the address of the machine code that handles that word. The interpreter either makes a subroutine call to that address (subroutine threaded), or jumps to that address (called "direct threaded" if I recall, where the handler jumps back to the interpreter instead of executing a RET).
But that's where my mental model of Forth breaks down, because IF-THEN-ELSE cannot be implemented in that model. So there must be something else fundamental in the Forth interpreter that I don't understand.
The missing bit is IMMEDIATE mode. Words can be tagged as IMMEDIATE, which means that they get executed at compile time (or parse time, for an interpreter), rather than a call to them getting compiled (executed at run time, for an interpreter). IF/ELSE/THEN are then "just" IMMEDIATE mode words -- but you can add your own. The "special sauce" is that IF compiles (easier to talk about for a compiler; generalize as needed) a conditional branch to an unknown address, and puts the address of that branch instruction (or an equivalent) on the /compile time/ data stack; THEN then looks at the address on the /compile time/ data stack and patches that instruction to branch to the correct address. Plenty of subtlety possible, but the basic primitive of IMMEDIATE mode is the key.
Are you saying that the Forth interpreter is a 2-pass interpreter? Or does the interpreter go into a special IMMEDIATE mode upon hitting the IF keyword, then it just consumes subsequent tokens without doing any dispatching, until it hits the THEN token? It sounds like nested IF-THEN-ELSE becomes tricky to handle.
How does the FORTH interpreter handle loops? Does the interpreter hit the WHILE token, goes into IMMEDIATE mode, remembers the location of the WHILE, then dispatches all the subsequent code, until it hits the REPEAT token, then branches back to the WHILE?
If understanding this special IMMEDIATE mode is required to understand the Forth interpreter for something as fundamental as control-flow, it seems fair to say that Forth is not a simple language. It's not just an advanced programmable RPN calculator An RPN calculator has a program counter, which makes control-flow easy to understand.
In comparison, C is a high level language, but the mapping from C code to assembly language is relatively simple. (Yes, compiler optimizations against the C "abstract machine" can make the resulting code completely obscure. But if we turn off optimization, the resulting assembly code matches the C code fairly directly.)
\ Run Time Code for Control Structures 04OCT83HHL \ \ Run Time Code for Control Structures 05MAR83HHL
CODE BRANCH (S -- ) \ BRANCH Performs an unconditional branch. Notice that we
LABEL BRAN1 0 [IP] IP MOV NEXT END-CODE \ are using absolute addresses insead of relative ones. (fast)
CODE ?BRANCH (S f -- ) \ ?BRANCH Performs a conditional branch. If the top of the
AX POP AX AX OR BRAN1 JE IP INC IP INC NEXT END-CODE \ parameter stack in True, take the branch. If not, skip
\ over the branch address which is inline.
\ Extensible Layer Structures 03Apr84map \ \ Extensible Layer Structures 03Apr84map
: ?CONDITION (S f -- ) \ ?CONDITION
NOT ABORT" Conditionals Wrong" ; \ Simple compile time error checking. Usually adequate
: >MARK (S -- addr ) HERE 0 , ; \ >MARK Set up for a Forward Branch
: >RESOLVE (S addr -- ) HERE SWAP ! ; \ >RESOLVE Resolve a Forward Branch
: <MARK (S -- addr ) HERE ; \ <MARK Set up for a Backwards Branch
: <RESOLVE (S addr -- ) , ; \ <RESOLVE Resolve a Backwards Branch
: ?>MARK (S -- f addr ) TRUE >MARK ; \ ?>MARK Set up a forward Branch with Error Checking
: ?>RESOLVE (S f addr -- ) SWAP ?CONDITION >RESOLVE ; \ ?>RESOLVE Resolve a forward Branch with Error Checking
: ?<MARK (S -- f addr ) TRUE <MARK ; \ ?<MARK Set up for a Backwards Branch with Error Checking
: ?<RESOLVE (S f addr -- ) SWAP ?CONDITION <RESOLVE ; \ ?<RESOLVE Resolve a backwards Branch with Error Checking
: LEAVE COMPILE (LEAVE) ; IMMEDIATE \ LEAVE and ?LEAVE could be non-immediate in this system,
: ?LEAVE COMPILE (?LEAVE) ; IMMEDIATE \ but the 83 standard specifies an immediate LEAVE, so they
\ both are for uniformity.
\ Extensible Layer Structures 01Oct83map \ \ Extensible Layer Structures 27JUL83HHL
: BEGIN ?<MARK ; IMMEDIATE \ These are the compiling words needed to properly compile
: THEN ?>RESOLVE ; IMMEDIATE \ the Forth Conditional Structures. Each of them is immediate
: DO COMPILE (DO) ?>MARK ; IMMEDIATE \ and they must compile their runtime routines along with
: ?DO COMPILE (?DO) ?>MARK ; IMMEDIATE \ whatever addresses they need. A modest amount of error
: LOOP \ checking is done. If you want to rip out the error checking
COMPILE (LOOP) 2DUP 2+ ?<RESOLVE ?>RESOLVE ; IMMEDIATE \ change the ?> and ?< words to > and < words, and
: +LOOP \ all of the 2DUPs to DUPs and the 2SWAPs to SWAPs. The rest
COMPILE (+LOOP) 2DUP 2+ ?<RESOLVE ?>RESOLVE ; IMMEDIATE \ should stay the same.
: UNTIL COMPILE ?BRANCH ?<RESOLVE ; IMMEDIATE
: AGAIN COMPILE BRANCH ?<RESOLVE ; IMMEDIATE
: REPEAT 2SWAP [COMPILE] AGAIN [COMPILE] THEN ; IMMEDIATE
: IF COMPILE ?BRANCH ?>MARK ; IMMEDIATE
: ELSE COMPILE BRANCH ?>MARK 2SWAP ?>RESOLVE ; IMMEDIATE
: WHILE [COMPILE] IF ; IMMEDIATE
When the interpreter is toodling along in compile state, compiling a colon definition by stowing pointers one after another (at the pointer here) into the definition of some word you're compiling, and it encounters an if, it sees that if is immediate, and so instead of stowing a pointer to if it just runs it immediately. The definition of if is compile ?branch ?>mark. compile is also an immediate word [correction, no, it's not, see below comment, though the following is still correct]; compile ?branch stows a pointer to ?branch into the colon definition being compiled, and then ?>mark writes a 0 into the entry following the ?branch and pushes true and the address of the 0 on the operand stack, at compile time, with the sequence true here 0 ,. The interpreter toodles along compiling the body of the if and eventually gets to, for example, then, which is also immediate, and is defined as ?>resolve, which overwrites the 0 into the address of the indirect-threaded code that will be compiled following the then. It does this with swap ?condition here swap !. The swap ?condition part aborts with an error if there isn't an unresolved if or similar on the stack to resolve, consuming the true, leaving only the address of the 0 that ?>mark had pushed. So then here swap ! overwrites that 0 with the current value of here.?branch is a word written in assembly which does a conditional jump in the inner interpreter (the one that interprets the indirect-threaded code); when it's executed, it pops a value off the stack and checks to see if it's zero, and if so, it changes the interpreter's execution pointer ip (which is defined elsewhere as the register si) to the number stored in the threaded code following the pointer to ?branch. If, on the other hand, the value it popped was nonzero, it increments ip twice to skip over that number. (Note that Laxen's comment on ?branch is incorrect in that it reverses the sense of the test.)
All the forward jumps work in pretty much the same way: when you begin a control structure you call ?>mark to write a zero placeholder and push its address, and later on you "resolve" that placeholder by popping its address off the stack and overwriting it with the correct address. leave (break) and ?leave (if (...) break) work slightly differently, but mostly the same.
Backward jumps work the other way around: when you begin a control structure, as in begin, you call ?<mark to save the current address on the stack so that you can jump to it later, which ends up just being true here. Then, to actually compile the jump, for example in until or again, you call ?<resolve, which ends up just being swap ?condition ,—the , pops the jump target address off the stack and compiles it into the indirect threaded code, serving as an argument the ?branch or branch instruction compiled immediately before it.
begin ... while ... repeat is handled, as you can see, by treating the while ... repeat part as an if ... then with an unconditional jump back to the begin jammed in right before the then.
Hopefully this is helpful!
BTW, for the above, I reformatted the block files from the F83 distribution with http://canonical.org/~kragen/sw/dev3/blk2unix.py, which you may find useful if you want to do the same thing.
https://github.com/dan4thewin/FreeForth2 This uses a two-pass search, for macros` and after that immediate words.
The most interesting one is Able forth https://github.com/ablevm which uses flow control to defer execution, aka quotations. I find using quotations instead of immediate modes easier to understand.
With both of these, they always compile expressions before executing them, so IF/THEN/ELSE can be used at any time.
That "IF" is implemented in terms of other more fundamental operators is fine, but can we write a program that just uses the fundamental operators that demonstrates IF-like behavior but doesn't introduce any intermediate words?
Yes, I think control-flow is easier to understand in assembly language than the implementation you showed in Forth. :-)
IF remembers its own location and reserves space for a jump; THEN compiles a conditional jump if NOT true to its location, in the place where IF was, unless there was an intervening ELSE, in which case it will compile such a conditional jump to ELSE's location at IF, and an unconditional jump to then just before ELSE. So a full use might look like:
: TEST > IF ." greater" ELSE ." less or equal" THEN ;
Which is the equivalent of: void test(x,y) {
if(x > y) {
printf("greater");
} else {
printf("less or equal to");
}
}
THEN works differently in Forth than in, like, BASIC. It marks the end of the whole conditional block, not the start of the consequent.figuring this out for my own FORTH interpreter was a moment i still remember, nearly 50 years later. quite a revelation
I would prefer to write in assembly language than write in Forth. Which is what I have done with one of my current projects.
With assembly language, there is a good chance that a random person with some minimal programming skills would understand my program if I were hit by a bus. With Forth, I think the chances of that are close to zero.
Immediate words are essentially a kind of macro, if it makes things easier for you.
i definitely prefer assembly to FORTH. i have direct and rather terrible experience with this after watching a few people try to ship a cartridge video game in FORTH
In most languages branching is a fundamental construct, it's created here (with comments)
https://github.com/cesarblum/sectorforth/blob/master/example...
Effectively IF compiles a 0= ie. If false and then a dummy target address. THEN (aka ENDIF) compiles the real target address over the dummy one, which is the address after THEN.
The article gives an example
> : buzz? 5 mod 0 = IF ." Buzz" THEN ;
Seems to work okay.What about immediate mode?
> 10 5 mod 0 = IF ." Buzz" THEN ;
action is not a function
Well, I guess that does it for me.Factor, another stack-based languages, has a more legible version of this, where you can push an anonymous lambda onto the stack. As I recall from my days of programming HP-48's, that used a similar mechanism. (Not checking my syntax here)
> 5 mod 0 = << "buzz" print >> if
Would have a similar effect. Each entry makes sense -- the << switches from immediate mode to store mode (or some similar concept), and everything ends up on the stack. "If" is just a function that takes a boolean and a closure: > 10
level: 0 ; stack: [10]
> 5
level: 0 : stack: [10 5]
> mod
level: 0 ; stack [0]
> 0
level: 0 ; stack [0 0]
> =
level: 0 ; stack [true]
> <<
level: 1 ; stack [true] []
> "buzz"
level: 1 ; stack [true] ["buzz"]
> print
level: 1 ; stack [true] ["buzz" print]
> >>
level: 0 ; stack [true pointer_to_function]
> if
"buzz"
level: 0 ; stack []
But I don't understand what Forth is doing.I will take a run at explaining IF ENDIF (endif is the Fig Forth term, used here to avoid confusion)
?BRANCH is an instruction in the virtual machine. It jumps if top of stack=0 . The offset (or address)that it jumps to is the memory word right after the ?BRANCH token. Like this: <?BRANCH><number>
Forth definition of IF
: IF COMPILE ?BRANCH HERE 0 , ; IMMEDIATE
At compile time IF "compiles" the token for ?BRANCH but then interprets "HERE 0 ,"
(IF is an IMMEDIATE word that executes even if the compiler is turned on)
HERE is like $ in Assembler, ie: the address where code is being laid down. It is simply left on the data stack. HERE is the address where the <number> will be stored... later.
0 is a zero, that is pushed onto the data stack.
"Comma" (,) pops the zero and puts it in memory address HERE but! it advances the system memory pointer 1 integer width.
The zero is now a place holder in memory to be filled in by ENDIF.
: ENDIF( addr -- ) HERE OVER - SWAP ! ; IMMEDIATE
ENDIF needs that address left behind by IF shown in comment as addr.
ENDIF gets the new value of HERE which of course is different because we will have compiled some code after the IF keyword.
All we need to do is do NEWHERE-OLDHERE to get the offset for ?BRANCH.
That is covered by the forth code ( oldhere-on-stack) HERE OVER -
This will make the data stack be: ( OLDHERE offset )
If we do a SWAP we just need the store operator '!' to put the offset into memory.
For the morbidly curious here is the definition of ELSE. :-)
: ELSE COMPILE BRANCH HERE 0 , SWAP [COMPILE] ENDIF ; IMMEDIATE
So loops are just more of the same... (all loops jump back to BEGIN. BRANCH is an unconditional jump instruction)
: BEGIN HERE ; IMMEDIATE
: AGAIN COMPILE BRANCH HERE - , ; IMMEDIATE
: UNTIL COMPILE ?BRANCH HERE - , ; IMMEDIATE
: WHILE [COMPILE] IF SWAP ; IMMEDIATE
: REPEAT [COMPILE] AGAIN [COMPILE] ENDIF ; IMMEDIATE
That brings us to the question, when it was invented and people did use it. What kind of problems were they solving with it?
The usual alternative to Forth on those systems was assembly language.
Nowadays almost nothing is written in Forth. That's the problem with Forth. Even on 8-bit Arduino microcontrollers with 2kiB of RAM, we write programs in C++ (with a little bit of C, on top of hand-coded AVR assembly).