Starting Forth : Extending the compiler

Hadrien W.
2 min readDec 16, 2017

--

In the previous post, I wrote about my progress through the 10th chapter of Starting Forth, by Leo Brodie. Today, we will move up a chapter and talk about defining and compiling words. Here are my answers to the exercises.

11.1 : In gforth, s”puts two values on the stack : the address of the string and the number of characters it contains, the count. As per the gforth documentation, in standard programs you should assume that the string lives only until the next s". T his is why we have to fetch the contents at the address and store them at a new place in memory instead of simply storing the address that was put by s” on the stack (this is done by the do loop). You would use this word to create new words like this : s" somefile.fs" loaded-by someword

11.2 : Words defined with based.print the element at the top of the stack in the base they were defined with, without changing the current base. At their run-time, we must store the current base in the return stack so that we can return back to it later. Use it so : decimal 16 based. h. 17 dup h. .It should return 11 17

11.3 : We save an execution token (the address pointing to a piece of compiled code) in a word and run it with a do loop.

11.4 : This was a bit tricky for me to figure out, despite being so simple.

11.5 : This was the hardest for me. I guess I’m still not really confortable with I/O in Forth. The interesting part of the exercise is that you easily can modify how the interpreter works. I decided that I would treat cases where the loop count is 1 in the same way as when it’s not valid (0 or negative) : ie. executing the rest of the line as if the loops function never happened. The program is poorly optimized, as you repeat the first test needlessly and get the same addresses and count over and over in the loop.

In conclusion, I think the ability to create new compilers (defining words) and to change the flow of compilation (with immediate, postpone, [ and ]) is what sets forth apart from other languages. It’s done quite naturally and without excessive overhead, which is always nice.

--

--

Hadrien W.
0 Followers

I work as a doctor in a psychiatry residency. I also like programming and sketching.