← Wed, Dec 2 digest

Writing a primitive Forth in JavaScript (2024)

read article ↗ hn thread ↗

This article walks through building a primitive Forth interpreter and compiler in JavaScript in roughly one hundred lines of code.

summary is enough The implementation is clean and concise, but experienced developers can grasp the core JavaScript Forth loop from the summary alone.

summary

The author implements a minimalist Forth interpreter and compiler in about one hundred lines of JavaScript as a stepping stone toward a bare-metal Forth OS. The post breaks down the core components, including the data stack, dictionary array, token parser, and the evaluation loop that handles switching between interpreter and compile modes. While lacking low-level byte addressing and advanced primitives, the prototype demonstrates how reflection and extensibility can be achieved with minimal code. It highlights why Forth remains an appealing, ultra-simple alternative to complex virtual machines.

key points

  1. A functional Forth core requires only a data stack and a dictionary array mapping tokens to functions.
  2. Compile mode is implemented by appending function calls to the definition body of the most recently created dictionary word.
  3. Backward dictionary searching ensures newer word definitions take precedence, enabling dynamic iteration and overrides.

who should read it

Hobbyist language implementers and developers interested in minimal virtual machines or stack-based languages.

discussion positive

consensus

Commenters debate the architectural compromises of implementing Forth in a high-level garbage-collected language like JavaScript, particularly regarding byte addressing, arrays, and performance.

pushback

Some argue that a JavaScript Forth should lean into dynamic typing and wrap native JavaScript objects rather than mimicking low-level byte buffers.

best comment by PaulHoule ↗

A FORTH in Javascript should do what Clojure does for Java.

The object on top of the stack should be a Javascript value, numbers are all doubles, and you can use strings, arrays, objects-as-dicts and in fact ordinary objects you could write something like

>> {"a": [1, 2], "b": "hello" }

>> DUP

>> "a" GET{ 0 GET[

>> .

1

>> "something" "c" PUT{

>> .

{"a": [1, 2], "b": "hello", "c": "something" }

You could use all the metaprogramming tricks you use in other FORTHs, be able to do anything Javascript can do, I don't think it would be too hard to unpack the stack and turn a word that …

It proposes a compelling alternative architecture where stack values are native JavaScript objects and maps, bridging Forth metaprogramming with the JS ecosystem.

Generated by an LLM from the article and thread. Check the sources before relying on it.