6 ms·
Lisp in Forth
- bifrost 6y agoThis is pretty cool especially since Forth is gaining interest in some circles.
- threatofrain 6y agoHow so?
- codezero 6y agoFor me I got interested in it while getting into some retro computing stuff during the pandemic, curious where others are getting that itch from! [1] Playing with open boot on my old iBook power PC - realizing it's a forth [2] Playing with durexForth on c64 emulators [3] collapse-os recently switching to forth.
- anthk 6y agoQemu PPC uses Forth too.
- monocasa 6y agoBecause OpenFirmware, the more or less standard bootloader of PowerPC and Sparc specified forth as it's command language. Even let you write PCI option ROMs in forth to have ISA independent boot drivers.
- codezero 6y agoI thought I bricked my 21 year old iBook and a forth command saved me. They don’t teach you that in algebra school.
- lebuffon 6y agoOpen Firmware written by Mitch Bradley is actually just a byte-code Forth custom extended to be the system firmware. :) So it's not that the language was specified but rather the language is the Firmware. By using byte-codes for the Forth keywords and allowing new wordlists to be created and extended you get a nice virtual machine that has the low-level chops to let you write device drivers and such, as you mentioned, while keeping the object code very small. It quite clever. Unfortunately Forth itself is so "other" that it can never win the popularity contest. However like Lisp it is one of those mind expanding paradigms that should be sampled for the insights into minimalist computing that it provides.
- anthk 6y agoBTw, is there a way to have numbers bigger than 2^15-1 in collapseOS'Forth, or under 8/16 bit Forths?
- codezero 6y agoDidn't get deep enough to need to test those limits, but I assume they would need to be hand rolled.
- frompdx 6y agoPersonally I came across FlashForth last year and have had a lot of fun hacking on my Arduino boards with Forth.
- bradrn 6y agoThanks for the recommendation! I have an Arduino and just started playing with Forth yesterday, so I’ll have to try this.
- frompdx 6y agoDon't forget to grab a programmer. I use a HiLetgo USBTiny programmer. They go for about $8. Also, do some googling about how to work with Forth on the Arduino. Not too much out there but it should help round out the FlashForth docs. arduino-forth.com is a good resource as well.
- bradrn 6y ago> Don't forget to grab a programmer. I use a HiLetgo USBTiny programmer. Hmm… I’m pretty inexperienced with Arduino (or indeed any microcontroller), so I have no idea what you’re talking about here. What’s a ‘programmer’? > arduino-forth.com Thanks for the link! Added to my reading list.
- frompdx 6y agoOne of these: https://www.amazon.com/HiLetgo-USBTiny-USBtinyISP-Programmer-Bootloader/dp/B01CZVZ1XM https://www.amazon.com/HiLetgo-USBTiny-USBtinyISP-Programmer... It allows you to burn the FlashForth bootloader on an Arduino, or to re-burn the Arduino bootloader if you'd like to program your Arduino with C/C++ instead of Forth. This blog has a good walkthrough of burning the FlashForth bootloader: https://rickcarlino.com/2017/05/26/up-and-running-with-flashforth-on-arduino-html.html https://rickcarlino.com/2017/05/26/up-and-running-with-flash...
- frompdx 6y agoIn addition to arduino-forth.com, definitely check out Starting Forth by Leo Brodie. It's a great book. Probably one of the best technical books out there. You can read it for free online. Sadly, it is out of print. You can find used copies though.
- Klwohu 6y agoIn my city it's becoming more popular than Rust in the hacker spaces.
- wsgeek 6y agoWhat general area if I may ask?
- tartoran 6y agoSmall is the new big. Not being serious but frameworks took the joy out of programming in a dogmatic way but lost a lot of the beauty and creativity in coding in exchange of too many features that a lot of the time we don’t need. People started looking at the past and what has been overlooked by many and started to bring it back. I am glad I starated learning Lisps and Scheme in particular. I don’t know why I like it so much but I am thankful people bring old things in fashion, even if for personal growth. My ignorance built upon the general consensus (what I thought of at the time) was that Lisp was a forget about proposition, that parantheses make it a horrible coding experience which couldn’t be further from the truth. I think i prefer this syntax now. Keep up exploring and sharing folks, you are making a dent.
- bifrost 6y agoPeople are just poking around with it because its a mature language thats been used for a lot of embedded things. Its been in several bootloaders as well. The FreeBSD bootloader uses it so I technically use it any time I boot my machine heh. Imagine being able to run LISP in the bootrom of a random machine :)
- sigjuice 6y agoThe FreeBSD bootloader made the switch to Lua.
- ajdude 6y agoOne of the circles that I am in, people have been realistically considering Forth for a bootstrapper; it's very easy to build up the rest of Forth using Forth once you have a minimal set of keywords implemented in assembly for your hardware of choice.
- guenthert 6y agoYeah, some circles. It's guys getting to middle-ages or retirement age, having more time on their hands, feeling a bit nostalgic and are tinkering. That's fine, I do have a weak spot for Lisp and FORTH myself, but don't confuse that with applicability in the industry.
- bifrost 6y agoThey said that about Javascript too and well... look at what we have now.
- asimjalis 6y agoHow fast is this?
- mark-probst 6y agoAuthor here. I never benchmarked it, but probably not fast. This was just a fun programming exercise.
- lebuffon 6y agoIt won't be extremely fast. This was discussed in comp.lang.forth a few years back. It's very interesting as an instructional tool but is not optimal for GForth. For example the symbol table is written in Forth whereas it would be faster to use GForth wordlists which give you a hashed lookup method. There is a string-to-number routine written but GForth has >NUMBER which can handle double precision conversions and is in the kernel. However it is all there and it works. For an experience Forth user it wouldn't take too much to improve it. If it was compiled on a native code Forth compiler like SwiftForth, iForth or VFX and with a few better uses of the internal system resources it would be fast enough to useful I suspect.
- FullyFunctional 6y agoNot this, but I wanted to make a Scheme VM and expose it directly, forth-like. A nice benefit would be a memory safe forth with advanced data types and GC. EDIT: to clarify, the point of this of course is to write only the minimal, performance critical piece (the VM) in native code and build a complete Scheme environment on top of this. There has been many similar efforts (Scheme48, VSCM, etc), but AFAIK none of them exposed the VM directly.
- RodgerTheGreat 6y agoOn a related note, here's a Logo interpreter I implemented many years ago using a dialect of Forth: https://github.com/JohnEarnest/Mako/blob/master/demos/Loko/Loko.fs https://github.com/JohnEarnest/Mako/blob/master/demos/Loko/L...
- kragen 6y agoThis is an awesome project! I think writing a bootstrapping Lisp is probably one of the best uses for a Forth. I was surprised that they said, "One of the more involved parts of this interpreter is the reader, where I had to do quite a lot of stack juggling to keep everything in line", and I think I can offer some useful pointers not only for the original author but also for anyone else who decides to go off and write stuff in Forth even though it's 02021. As it happens, I coded up just Lisp READ and PRINT in Forth the other day, and I avoided doing any stack juggling at all: http://canonical.org/~kragen/sw/dev3/readprint.fs http://canonical.org/~kragen/sw/dev3/readprint.fs My READ is 14 lines of Forth, and even accounting for the more horizontal (not to say cramped) layout of my code and its lack of symbol support, I think it's still significantly simpler and more readable than the 60 or so lines of Forth used here. Contrast: : lisp-skip-ws ( e a -- e a ) lisp-read-char begin dup 0<> over lisp-is-ws and while drop lisp-read-char repeat 0<> if lisp-unread-char endif ; with (slightly reformatted) : wsp begin peek bl = while getc drop repeat ; There are four simplifications here: 1. My definition of "whitespace" is just "equal to the space character BL". Arguably this is cheating, but it's a small difference. 2. I'm handling EOF with an exception inside PEEK, rather than an extra conditional case in every function that calls PEEK; this implies you have to discard whitespace before your tokens rather than after them, but that's what both versions are doing anyway. 3. I'm using a high-level word PEEK to represent the parser-level concept of "examine the next character without consuming it" rather than the implementation-level concept "dup 0<> over". This is facilitated by putting the state of the input stream into the VALUEs READP and READEND instead of trying to keep it on the stack, which would have given me a headache and wasted a lot of my time debugging. PEEK and GETC can always be called regardless of what's on the stack, while LISP-READ-CHAR only works at the beginning of an "expression". 4. The choice of the PEEK/GETC interface instead of GETC/UNGETC is also a very slight improvement. It would be less of a difference if LISP-UNREAD-CHAR were capable of unreading an EOF, but in general to the extent that you can design your internal interfaces to avoid making temporary side effects you must undo later, you will have less bugs from forgetting to undo them. In other parts of the code the situation is somewhat worse. Consider the mental gymnastics needed to keep track of all the stack state in this word: : lisp-read-token ( e a -- e a a u ) lisp-skip-ws 0 >r lisp-read-char begin dup [char] ) <> over 0<> and over lisp-is-ws 0= and while token-buffer r@ + c! r> 1+ >r lisp-read-char repeat 0<> if lisp-unread-char endif token-buffer r> ; I didn't have a separate tokenizer except for READ-NUM, because all my other tokens were parentheses. But contrast: : (read-num) 0 begin eod? if exit then peek [char] - = if -1 to (sign) getc drop else peek isdigit if getc digit else exit then then again ; \ That took me like half an hour to debug because I was confusing char \ and [char]. : read-num 1 to (sign) (read-num) (sign) * int2sex ; Mine is not beautiful code by any stretch of the imagination. But contrast PEEK ISDIGIT IF GETC DIGIT ELSE EXIT THEN — in popular infix syntax, that would be if (isdigit(peek()) then digit(getc()) else return — with TOKEN-BUFFER R@ + C! R> 1+ >R LISP-READ-CHAR! Imagine all the mental effort needed to keep track of all those stack items! Avoid making things harder for yourself that way; as Kernighan and Plauger famously said, debugging is twice as hard as writing the code in the first place, so if you write the code as cleverly as you can, how will you ever debug it? You can define words to build up a token and write your token reader in terms of them: create token-buffer 128 allot token-buffer value tokp : token-length tokp token-buffer - ; : new-token token-buffer to tokp ; : token-char tokp c! tokp 1+ to tokp ; Or, if you prefer (untested): create token-buffer 128 allot variable token-length : new-token 0 token-length ! ; : token-char token-buffer token-length @ + c! 1 token-length +! ; Or similar variations. Either way, with this approach, you don't have to keep track of where your token buffer pointer (or length) is; it's always in tokp (or token-length), not sometimes on the top of stack and sometimes on the top of the return stack. In this case the code doesn't get shorter (untested): : lisp-read-token ( e a -- e a ) lisp-skip-ws new-token lisp-read-char begin dup [char] ) <> over 0<> and over lisp-is-ws 0= and while token-char lisp-read-char repeat 0<> if lisp-unread-char endif ; but it does get a lot simpler. You don't have to wonder what "0 >R" at the beginning of the word is for or decipher R@ + C! R> 1+ >R in the middle. You no longer have four items on the stack at the end of the word to confuse you when you're trying to understand lisp-read-token's caller. And now you can test TOKEN-CHAR interactively, which is helpful for making sure your stack effects are right so you don't have to debug stack-effect errors later on (this is an excerpt from an interactive Forth session): : token-type token-buffer token-length type ; ok token-type ok char x token-char token-type x ok char y token-char token-type xy ok bl token-char token-type xy ok .s <0> ok new-token token-type ok char z token-char token-type z ok This is an illustration of a general problem that afflicted me greatly in my first years in Forth: just because you can keep all your data on the stack (a two-stack machine is obviously able to emulate a Turing machine) doesn't mean you should. The operand stack is for expressions, not for variables. Use VARIABLEs. Or VALUEs, if you prefer. Divide your code into "statements" between which the stack is empty (except for whatever the caller is keeping there). Completely abjure stack operations except DROP: no SWAP, no OVER, and definitely no ROT, NIP, or TUCK. Not even DUP. Then, once your code is working, maaaybe go back and put one variable on the operand stack, with the appropriate stack ops. But only if it makes the code more readable and debuggable instead of less. And maaaybe another variable on the return stack, although keep in mind that this impedes factoring — any word you factor out of the word that does the return-stack manipulation will be denied access to that variable. Think of things like SWAP and OVER as the data equivalents of a GO TO statement: they can shorten your code, sometimes even simplify it, but they can also tremendously impede understandability and debuggability. They easily create spaghetti dataflow. Failure to observe this practice is responsible for most of the difficulty I had in my first several years of Forth, and also, I think, most of the difficulty schani reports, and maybe most of the difficulty most programmers have in Forth. If you can figure out how you would have written something in a pop infix language, you can write it mechanically in Forth without any stack juggling (except DROP). For example: v := f(x[i], y * 3); if (frob(v)) then (x[j], y) := warp(x[j], 37 - y); becomes something like this, depending on the particular types of things: i x @ y c@ 3 * f v ! v @ frob if j x @ 37 y @ - warp j x ! y c! then Now, maybe you can do better than the mechanical translation of the infix syntax in a particular case — in this case, maybe it would be an improvement to rewrite "v ! v @" to "dup v !", or maybe not — but there's no need to do worse. This is not to diminish schani's achievements with forthlisp, which remains wonderful! I haven't ever managed to write a Lisp in Forth myself, despite obviously feeling the temptation, just in C and Lua. Code that has already been written is far superior to code that does not exist. But, if they choose to pursue it further, hopefully the fruits of my suffering outlined above will nourish them on their path, and anyone else who reads this.
- daladd 6y agoThis is funny -- my class project in Semantics of Programming Languages in '88 at Univeristy of Illinois was essentially "Forth in Lisp".
- jedimastert 6y agoI was just thinking of a project. I don't know Forth or Lisp very well, so instead of bootstrapping one or the other, I could make a Forth that could compile the Lisp and a Lisp that could compile the Forth
- fao_ 6y agoAhhhhhh. I was daydreaming this the other day
- timonoko 6y agoLisp is Forth where "(" pushes next word onto separate execution stack and ")" executes it. Hence (+ 1 2) is equal to 1 2 +. I made this discovery maybe 1975, but Forth was not yet invented, or rather Internet was not yet invented, so I did not know about Forth. So it was a property of my very own Symbolic Stack Machine on Nova 1200.
- kaba0 6y agoI’m not too familiar with LISPs, but that would only be the case with greedy evaluation, wouldn’t it?
- timonoko 6y agoEh. What. It is regular Forth with one additional stack. Except in real Forth "()" is reserved to something else.
- nils-m-holm 6y agoYes. (And that's what every LISP I know does.)
- monistowl 6y agoSomething like this would make an excellent way to extend Collapse OS, if only it implemented GForth structs... https://collapseos.org/ https://collapseos.org/
- DonHopkins 6y agoForth Illustrated -- the August 1980 Byte Magazine cover: https://archive.org/details/byte-magazine-1980-08 https://archive.org/details/byte-magazine-1980-08 That's how it looks in my head, beveled stones and threads and stars and all.
- gardenfelder 6y agoThat's the article which got me started with Forth for use in microprocessor-based weather stations. I eventually did write a scheme interpreter - as well as an SQL interpreter; a friend then wrote a scheme compiler, which ran scheme in forth code 28 times faster. I wish I could resurrect that code, but it was saved to an ancient cd disk in the Apple compressed mode, and that file will not open now.