hn.today

Writing a primitive Forth in JavaScript (2024)

onirom.fr37 points18 comments
Screenshot of Writing a primitive Forth in JavaScript (2024)

Forth is introduced as a minimalist, stack-oriented language in which space-separated words operate on data and programs are composed from those words, usually in postfix notation. A roughly 100-line JavaScript prototype demonstrates the core idea as an extensible interpreter and virtual machine, built partly with p5.js for a graphical command-line interface. Its small vocabulary includes `:` and `;` to define words, `+` and `-` for arithmetic, `.` to display the stack’s top value, and `WORDS` to list definitions; unrecognized tokens are treated as numbers when possible. The project began as a way to learn about language implementation and later informed a bare-metal Forth environment for ARM.

The implementation centers on a data stack and a dictionary containing both built-in primitives and user-defined words. Input is split into tokens, matched against dictionary entries, and evaluated or compiled according to the interpreter’s mode; definitions are assembled from the functions associated with their component words. The prototype is deliberately incomplete and nonstandard: it lacks practical essentials such as stack-manipulation and I/O operations, though these can be added as further primitives. Its simplicity illustrates Forth’s reflective, extensible design: control structures and other language features can likewise be built from compact operations, without an abstract syntax tree. Postfix notation may take practice, but avoids more complex parsing; parentheses or an infix-to-postfix conversion could improve familiarity. Further steps include writing the REPL in Forth or generating lower-level code.

Read on onirom.fr18 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

Laravel Go

Laravel Go

Laravel for Go is a full-stack web framework with routing, validation, database tools, background jobs, workflows, and real-time events. It also supports Inertia for frontend integration and is open source under the MIT license. (github.com)

Laravel Go

Laravel Go

Laravel Go is a batteries-included Go framework that combines routing, data access, authentication, queues, workflows, and other features in one package. It uses standard Go patterns and Inertia to serve React, Vue, or Svelte pages without separate API boilerplate. (laravel.com)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.