Urgent.News

What's breaking now, across thousands of outlets.

Tech

How I Wrote a Forth (Without Knowing How)

Several weeks ago, the author embarked on creating an implementation of the Forth programming language, initially unaware of how to write a Forth. This process proved remarkably simple, with little to remark upon. The author found little guidance on writing a Forth, so they began with JonesForth, a Forth written in x86 assembly language, as a reference.

The author chose not to directly translate JonesForth's assembly code, finding it too verbose, and sidestepped the interpreter and compiler. Instead, they focused on writing functions to manipulate Lua's stack using Lua's C API, treating these functions as core Forth words. This approach proved beneficial, as Lua's stack manipulation made it easier to write more complex functions.

By treating Forth words as a series of other words, the author stored custom word definitions as tables of pointers to C functions. This allowed for word redefinition, similar to most Forth systems. Storing string and number literals in word definitions also proved straightforward, enabling the interpreter to read types and determine appropriate actions.

The author feared they might complete the work, but their first line of code ran three days after starting. Compilation and alignment with the interpreter came soon after. The author implemented core language features such as immediate words, flow control (if/else/then statements and loops), and afterward, completed the implementation within a week. Despite not closely following JonesForth's source code, MoonForth ended up with the same core language features.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at vtrlx.ca →

More in Tech

More from Tuesday 15 September →