104 points · by tosh · 6y ago · 53 comments
A sometimes minimal FORTH compiler and tutorial for Linux / i386 systems by Richard W.M. Jones
"LISP is the ultimate high-level language, and features from LISP are being added every decade to the more common languages. But FORTH is in some ways the ultimate in low level programming. Out of the box it lacks features like dynamic memory management and even strings. In fact, at its primitive level it lacks even basic concepts like IF-statements and loops.
Why then would you want to learn FORTH? There are several very good reasons. First and foremost, FORTH is minimal. You really can write a complete FORTH in, say, 2000 lines of code. I don't just mean a FORTH program, I mean a complete FORTH operating system, environment and language. You could boot such a FORTH on a bare PC and it would come up with a prompt where you could start doing useful work. (...)
Secondly FORTH has a peculiar bootstrapping property. By that I mean that after writing a little bit of assembly to talk to the hardware and implement a few primitives, all the rest of the language and compiler is written in FORTH itself. Remember I said before that FORTH lacked IF-statements and loops? Well of course it doesn't really because such a lanuage would be useless, but my point was rather that IF-statements and loops are written in FORTH itself."
https://github.com/nornagon/jonesforth/blob/master/jonesfort...
[0] https://archive.org/stream/R.G.LoeligerThreadedInterpretiveL...
I like the feeling of concatenative languages. I especially seem to like the postfix notation over prefix and largely this creates the paradigm of lisp vs forth at first step - in my opinion.
I’ve recently dug in to Factor and it’s quite an amazing piece of art that is highly usable and up to date despite such a small community. It almost feels like a secret weapon and too good to be true. I’m having a ton of fun hacking on it. It’s like Smalltalk and forth had a baby.
I dream of making an OS with Forth/Factor similar to Plan9 and Oberon.
I get a kick out of Forth being made of words and Genesis from the Bible.
At first was the Word, and the Word was with Forth, and the Word was Forth.
https://en.wikipedia.org/wiki/Oberon_(operating_system)
Tidbit if anyone cares: I’ve been obsessing over returning to first principles of computing. I’m bored of the internet and browsers. I want to have fun with software AND hardware and Forth seems like such a perfect language to do exactly that with. Factor is a nice grown up example of that but it’s definitely a few steps removed from portability and self bootstrapping behavior like in CollapseOS.
Retro Forth is extremely impressive: http://forth.works
Oberon System 3 with its gadgets framework or the current AOS (still used as teaching tool at ETHZ) also have interesting ideas, and better support for systems programming.
The book "The Oberon Companion. A Guide to Using and Programming Oberon System 3" is available as part of the System 3 environment delivered as part of AOS.
http://builds.cas.inf.ethz.ch/
You can find some old ISOs from here https://github.com/cubranic/oberon-a2
Also, following on from A2, Composita introduces a component architecture to allow managed memory without GC, and contextless switches:
http://concurrency.ch/Content/publications/Blaeser_Component...
IMHO better than Rust, and I'd love to see this style of memory management paired with a minimal lisp eg. https://piumarta.com/software/maru/
so we can build more deterministic high-level structures
Also have a look at Mesa/Cedar, as it was the inspiration for Oberon ideas.
https://news.ycombinator.com/item?id=24450970
Comments include a link to one hour demo on YouTube with members of the team.
As idea, many of these concepts can be done on modern OSes, on top of something like COM/D-BUS/gRPC/XPC, but none of them go as far as they did.
The “hook” for me was seeing things like ifs and loops being written in Forth itself from simpler primitives. I’ve always been a fan of bootstrapping a general purpose computing environment from a small set of primitives, and Forth lets you do exactly that.
> I’m bored of the internet and browsers. I want to have fun with software AND hardware
I can 100% relate to that feeling. Discovering Forth has been therapeutic for me in a sense. I spend the day dealing with AWS and Java and logs and metrics for large distributed systems, and that brings me zero joy or motivation. I spend my work days looking forward to my time with Forth in the evening.
I think it was CollapseOS that sent me down this rabbit hole :)
"My minimal stack of layers is – problem, software, hardware. People working on the problem (algorithms, UI, whatever) can't do software, not really. People doing software can't do hardware, not really. And people doing hardware can't do software, etc.
The Forth way of focusing on just the problem you need to solve seems to more or less require that the same person or a very tightly united group focus on all three of these things, and pick the right algorithms, the right computer architecture, the right language, the right word size, etc. (...)
So you need at least 3 teams, or people, or hats, that are to an extent ignorant about each other's work. Even if you're doing everything in-house, which, according to Jeff Fox, was essentially a precondition to "doing Forth". So there's another precondtion – having people being able to do what at least 3 people in their respective areas normally do, and concentrating on those 3 things at the same time. Doing the cross-layer global optimization.
It's not how I work."
https://yosefk.com/blog/my-history-with-forth-stack-machines...
That’s largely where we are today in many sectors of society. Experts who only understand the nuances of a niche layer they’ve patched into a series of layers of indirection by the result of not taking the time to fully understand what one is working with from first principles or fundamentals. The OS’s of today are computation stacks that resemble something like bandaids and house of cards with people piling on intricate complexity without conceptual understanding that can be effectively reasoned about.
I understand that simple is hard. However when one can reason about a system when it fits entirely in their head then they can extend it completely. I believe all systems should be this way. To have anything else is a risk of corruption or assimilation as the minority control a majority through complexity against time.
Sorry I kind of went off on a tangent there.
Tl:dr systems should fit in anyone’s ability to reason about it conceptually. Anything too complex is an attack vector and disaster waiting to happen.
(Edited to add that while I haven't done any significant Forth work in probably 20 years, I've long been intrigued by Factor and I keep meaning to try 8th, as I've got some small simple program ideas that would be lovely to be able to run on Mac, iOS, and Android.)
Oberon inspired Acme and pforth runs on plan 9: https://github.com/Plan9-Archive/pforth9 (Factor cant be built on plan 9 due to the lack of c++ feature.)
I went through a forth phase and realized that its a good fit within the industrial control and motion segments. I started writing a motion control library I called forthaxis which took coordinates and spat out trajectory commands for servo drives. Didn't get very far but it was a fun exercise.
https://en.wikipedia.org/wiki/Jupiter_Ace
Edit: I never used one (or indeed ever saw one) but for some reason reading about Forth at the time gave me a lingering fascination with Forth type languages - which was useful when I worked on a project for a few years that used PostScript, C & Lisp ...
Forth is an extensible virtual machine
Most interpreted languages that are implemented with a virtual machine (sometimes known as a bytecode interpreter) have a fixed set of instructions. Modulo some implementation details, writing new Forth words is akin to extending the virtual machine with new instructions.
However, the article's Forth is a more extensible form of this. The entire evaluation of the virtual machine is split into an extensible set of states (starting with only interpret, compile, head, forth, lit), new types of instructions can be introduced by adding to a list of heads (starting with only DOCOL and EXIT), and then words are, specifically, lists of addresses that the forth state interprets, whose evaluation is triggered by a DOCOL seen in the head state.
This opens up possibilities to define other sorts of interpreters for specific purposes. The article gives the example of polynomial evaluation, but you could also do something like have a variant of the forth state for token threaded code in memory-constrained environments. Sort of like how ARM has an additional Thumb instruction set.
More detail for this last idea: you'd have an array of, say, 256 pointers, and in the bforth state you'd read the next byte of the thread, look up the address in the table, push it on the RS, then go into the head state. This gives you perfect interoperability. You'd just need a special bcompiler state that would look up the bytecode for each word.
I've read similar ideas on Lisp. I don't put much stock in it in either context, but I think Lisp has a better claim to extensibility. All programming languages enable decomposition of a program. Functions/methods/macros/words don't really 'extend' a language.
You can't easily add garbage collection to Forth. You can't easily add static type-checking to Forth. Why call it 'extensible'? It's no more extensible than C.
It may be easier to hack on a Forth implementation than a C compiler, sure.
The fact that this is exposed inspires a certain way of programming, and this seems to be essential to the Forth way.
This isn't saying too much about the language itself.
Extensibility refers to the ability to extend the compiler directly in the language. Lisp supports this with macros, which are not functions and are different than macros in C because they alter the behavior of the compiler, and Forth supports this with defining words and compiling words, which behave differently from other forth words because they alter the behavior of the compiler. Compare this to a macro in C, which pre-processes the macro into more C prior to compilation rather than at the time of compilation. In this respect, both Forth and Lisp are more extensible than C because facilities to extend the language exist within the language itself.
How about BOOST_SCOPE_EXIT in C++? [0] Is it extending the language, or just a trivial macro-based hack on RAII? What's the difference?
My other issue with it is that the major features of programming languages that people actually care about, aren't the kinds of things you can implement with clever macros. They tend to rely on serious engineering.
Even in a highly extensible language, you can't easily throw together features like industry-strength garbage collection, or a type system, or borrower-checking. (I considered listing formal verification but that would be unfair, it can't really be added to an existing language.) These things are implemented by compiler engineers, and always will be. (If I'm mistaken about that, and am underestimating anything, I'd be interested to know, but I don't think I am.)
What's the 'killer example' of LISP macros? I can see a pretty neat example at [1].
[0] https://www.boost.org/doc/libs/release/libs/scope_exit/doc/h...
[1] https://docs.racket-lang.org/guide/pattern-macros.html#%28pa...
These days, I wonder if it's possible to run Forth inside a VM as the operating system. How hard would it be to stand up a networking stack?
This would be reasonable afternoon project (except for the optimization stuff).
None of the C code is complex or tricky or big. You could easily do it in assembly instead. That's why these kind of languages are great for a lot of embedded applications. You only need to write a small assembly core to support your language, plus assembly function to support your hardware, and then you can do everything else in your higher level FORTH-like language.
Thanks again, four years later!
I'll get the compilation phase done tomorrow, barring surprises.
> loader [...] provides a scripting language that can be used to automate tasks, do pre-configuration or assist in recovery procedures. This scripting language is roughly divided in two main components. [...] The bigger component is an ANS Forth compatible Forth interpreter based on FICL, by John Sadler.
> [...]
> BUILTINS AND FORTH
> All builtin words are state-smart, immediate words. If interpreted, they behave exactly as described previously. If they are compiled, though, they extract their arguments from the stack instead of the command line.
> If compiled, the builtin words expect to find, at execution time, the following parameters on the stack:
> addrN lenN ... addr2 len2 addr1 len1 N
> where addrX lenX are strings which will compose the command line that will be parsed into the builtin's arguments. Internally, these strings are concatenated in from 1 to N, with a space put between each one.
> If no arguments are passed, a 0 must be passed, even if the builtin accepts no arguments.
> While this behavior has benefits, it has its trade-offs. If the execution token of a builtin is acquired (through ' or [']), and then passed to catch or execute, the builtin behavior will depend on the system state at the time catch or execute is processed! This is particularly annoying for programs that want or need to handle exceptions. In this case, the use of a proxy is recommended. For example:
> : (boot) boot;
> FICL
> FICL is a Forth interpreter written in C, in the form of a forth virtual machine library that can be called by C functions and vice versa.
> In loader, each line read interactively is then fed to FICL, which may call loader back to execute the builtin words. The builtin include will also feed FICL, one line at a time.
> The words available to FICL can be classified into four groups. The ANS Forth standard words, extra FICL words, extra FreeBSD words, and the builtin commands; the latter were already described. The ANS Forth standard words are listed in the STANDARDS section. The words falling in the two other groups are described in the following subsections.
https://www.freebsd.org/cgi/man.cgi?query=loader&apropos=0&s...