by s-macke · 1y ago · 0 comments
vdupras is here in the comments today. He's written a self-hosting interactive operating system in Forth, including a FAT16 filesystem and everything, and a compiler for a useful subset of C: https://duskos.org/
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.
\ 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.
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).
Actually I did a few projects with Forth and I find it very cool:
[0] https://github.com/s-macke/Forthly
[1] https://github.com/s-macke/starflight-reverse
[2] https://s-macke.github.io/concepts-of-programming-languages/...
Additionally, check basis/ and extra/ on https://github.com/factor/factor. You will find A LOT of goodies there. They even have a framework for Discord bots using latest Discord API version, if you are into that. In any case, you really ought to check, there are too many things to list here.
As someone else pointed out, it is 0.100 which was released not that long ago, and if you compile now, it is 0.101 anyways, but regardless of their versioning, it has been actively maintained ever since, they just did not bump the version for a long time.
Micropython can be similar this way, but it's more constrictive.
Just because you don't specifically use forth does not mean forth is dead.
Forth itself is hard to categorize since it refuses to standardize but we all know what it looks like, I'd say its a low level language/VM that manages everything through stacks (usually 2) there's forthlike languages and also concatenative languages. concatenative languages can be far removed from forth, I don't mean that the shell itself is concatenative, but only the shell pipelining aspect, which you can imitate in any forth. take an object and keep passing it to subsequent functions without popping that know s how to handle that object, that's a shell pipeline to me, all of unix can be passed the /dev/std* objects and they can all modify it and pass it along to the next function/program.
But you said, "Just because you don't specifically use forth does not mean forth is dead," and unless I misread your intent, you included your shell-scripting point on the theory that it was relevant to that question: whether or not Forth was dead. The implication seemed to be that, as long as people were using shell pipelines, Forth wouldn't be dead. But that's wrong; Forth could be totally dead while other forms of concatenative programming were alive and well.
There weren't a lot of languages which would fit in a tiny space, but FORTH was one of them. Like LISP it's a language where you can (1) implement the language without any kind of recursive parser and (2) write control structures in the language itself because each "word" in forth has both a run-time and compile-time interpretation.
Jupiter ACE had its followers, and it was common to see ads on Your Sinclair and similar magazines for ROM replacements using Forth instead of BASIC.
My favorite minicomputer BASIC that I got to use was on RSTS/E on the PDP-11 which had split 64k address spaces for code and data and used fairly advanced compilation techniques. Roughly the RSTS/E experience was like having your own Apple ][ but with a hard drive and a little more oomph. I grew up in New Hampshire right next door to DEC's headquarters in Massachusetts and there were DEC minicomputers everywhere.
Microsoft had a compiled BASIC (like run a compiler, not compile interactively like Microware's BASIC09) on CP/M for the Z-80 which was a much better compiler target than the popular 6502.
I wrote a FORTH for the TRS-80 Color Computer using the OS-9 operating system which had maybe 2000-3000 lines of assembly code. FORTHs at the time often did block I/O directly to the disk but OS-9 had an API to access files that was pretty similar to Unix and my FORTH exposed that.
These two languages represent diametrically opposed approaches to programming language design.
Were there anything in the crypto space is actually solving a problem is up to your own biases and prejudices. But if you pick one thing as actually trying to solve a real problem, payments over lightning is probably that. Lightning, at its core, is a state machine composed of Forth spend scripts.
This is like saying JSON is C++.
- Accounting system used for real life taxation in my self-employment: https://gist.github.com/lf94/fcdf41776e14fcc289bac652ea8cb4f...
- Software shader rasterizer for image generation: https://gist.github.com/lf94/f74c927e59b4010d9de001fa2ba8791...
- PS4 controller macro system via an RP2040 & ZeptoForth: https://youtu.be/exayMSQfyqk, https://gist.github.com/lf94/2d64917728594516dee6caf7667d2e4...
- Iambic paddle tap interpreter for morse code practice (once again running RP2040 & ZeptoForth): https://gist.github.com/lf94/95516fa39c3339b685e0fde10f17c97...
- Fixed-point number library to run computations on pretty much any CPU in existence: https://gist.github.com/lf94/ca622ebac14d48915ea976f665f832c...
- 1-bit music synthesis experiments to learn how to make music with a beeper (useful in products, such as Tile): https://www.youtube.com/watch?v=IjTihhFG03o, https://www.youtube.com/watch?v=_6f8PURcPEE
And that's all in my rare spare time.
Forth really shines in microcontroller or esoteric computation machines, but further more, people don't realize their C compilers are billions of dollars of development, and they'd never be able to do it in the first place. A Forth on the other hand can be developed in a month (I'm being honest-to-god realistic here. A lot of people would say "a weekend", but let's be real, anything useful will be more than a weekend. I'm trying to convince you this isn't bullshit :)).
If you have any more questions let me know. I was bit by Forth about 2 years ago but had read about it long ago when I was like 16 and passed it off as too hard. It's the same shit as when FP took off: it's a different mental model, so it will take time to morph your mind.
Edit: read the larger comment below, and they are totally correct:
> most Forth tutorials today are written by people who don't really know Forth
One day I might write a small Forth novella teaching how to actually think about Forth programs. In these 2 years I've had to just practice and write programs to see common patterns or idioms - kind of exactly like when I was learning Haskell years ago.
I don't think it takes billions of dollars in development to write a C compiler, but it does seem like everyone's first C compiler does take at least a year, so US$100k is a good ballpark. I agree that Forth is about an order of magnitude easier. You probably shouldn't consider https://github.com/kragen/stoneknifeforth to actually be a Forth (it's not interactive and doesn't have immediate words) but it did compile itself into a working ELF executable and it did take me almost exactly a month to write (October 02008, specifically). I could probably write a real Forth now in a month.
I would be very excited to read your small Forth novella. Or your small Haskell novella.
By contrast, assembly language underpins most software people run today: perhaps it's written in Python, which is interpreted by CPython (using a bytecode which is considerably more Forthlike than Wasm, incidentally), which is written in C, which is usually compiled by GCC or LLVM to textual assembly language in order to generate the executable.