Stkmach: a compiler in kakscript to kakscript

I’ve announced kak-stkmach before, but maybe there are enough developments to warrant a new post.

stkmach is now a Forth interpreter/compiler in (almost) pure kakscript, capable of loading the Forth test harness and passing relevant tests (a modified Forth 2012 testsuite).

There is a new runtime capable of emulating unstructured jumps (just as in assembly), and a Forth compiler to go along with. How does this work? Via a trampoline loop (a “driver”) and an explicit return stack (a str-list). Jumps trigger a kak exception that tells the driver to pop the return stack and call the command on top.

The compiler, on the other hand, generates code suitable for this runtime. In particular, since it is impossible to return from a trampoline jump, it splits code into separate pre-call and post-call commands.

See the implementation details, or just set ff-config-verbose 7 and play around.

A code generation example:

:ff| : ex if 10 . then 11 . \;
\ ff-msg[5]: compiled: ex = ff-xtcode-237
\ ff-msg[7]: compiled: def ff-xtcode-237 %{ ff-driver1-0jump-to 238;ff-stack-push 10;ff-xtcode-48 %opt{ff_stack};ff-driver1-jump-to 238; }
\ ff-msg[7]: compiled: def ff-xtcode-238 %{ ff-stack-push 11;ff-xtcode-48 %opt{ff_stack}; }


Here xtcode-48 is the handler for . (print). The code tests the top-of-stack and if false (0jump) skips printing 10. Either way, the compiled code trampoline-jumps to xtcode-238 (printing 11). The stkmach README has more examples and details.

3 Likes