26 May 2023

Adventures in Forth/Stack Languages, part 1

Over the last week I have been playing with a Forth-like language that I have implemented (separately) in JavaScript and C.

I have embedded the JavaScript version below, and both versions are available on Codeberg: https://codeberg.org/DanielRHolland/forth-style-stack-lang.

Update (30th May 2023): The version embedded below is now the C version, compiled to WebAssembly.

Commands:

  • Branching: if <tokens> then -, pop value from stack. If false/0, then skip all tokens between if and then. E.g. : f 1 1 = if 5 . then 8 . ; f will output 5 followed by 8, and : f 0 if 5 . then 8 . ; f will only output 8. (In forth, if can only be used inside user-defined functions, which is why the examples create a function f, before immediately calling it.)
  • Arithmetic: + - / * , pop 2 values form the stack, apply op, push result back to stack
  • Pop: . pop and print value
  • Peek: peek peek and print value
  • Stack manipulation: dup (copy top item),swap (swap top two),drop (drop top item),rot (rotate top three: top becomes second, second becomes third, third becomes first).
  • = pop two values, push true to stack if they are equal, else push false
  • not pop one value, push true if it is false/0, else push false
  • : <name> <tokens> ; define new command, first word after : is the name, the following tokens will be inserted in its place when it is evaluated, up until the ;.
    • E.g. : countdown dup 0 = not if peek 1 - countdown then ; creates a command that can be called like the builtin commands are: 5 countdown.
    • Use recursion to loop! (for now)
    • Another example: : dump dup if . dump then ; to pop and print the stack until the first false/0 value.
    • Multiplication implemented using addition and recursion: : multrec over if rot swap over + rot 1 - swap multrec then ; : mult 0 multrec ; 6 8 mult .
Tags: Forth C Tech