examples

Toy examples in single C files.
Log | Files | Refs

commit 7f468e9155e4ea68b86dc56e85be7f29e832633c
parent 2ab69cd62797c8ed33a89ff22c276d609eb94ca2
Author: Henry Wilson <henry@henryandlizzy.uk>
Date:   Thu, 25 Nov 2021 21:25:28 +0000

Add token threaded FORTH

Diffstat:
Asrc/token-threaded-forth.cpp | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 92 insertions(+), 0 deletions(-)

diff --git a/src/token-threaded-forth.cpp b/src/token-threaded-forth.cpp @@ -0,0 +1,92 @@ +#include <cstdint> +#include <iostream> + +#define LITERAL(x) DOLIT, x + +enum : unsigned char +{ + EXIT, + DOLIT, + DUP, + PRINT, + CR, + ADD, + NEGATE, + INCREMENT, +}; + +int main() +{ + void const* const tokens[] = + { + &&exit, + &&dolit, + &&dup, + &&print, + &&cr, + &&add, + &&negate, + &&increment, + }; + char const code[] = + { + LITERAL(6), + DUP, + PRINT, + CR, + + LITERAL(101), + DUP, + PRINT, + CR, + + ADD, + PRINT, + CR, + + EXIT, + }; + std::intptr_t stack[1024]; + char const* return_stack[1024]; + char const** ret = return_stack; + + std::intptr_t* top = stack; + char const* instruction = code; + +next: + goto *tokens[*instruction++]; + +dolit: + *top++ = *instruction++; + goto next; + +dup: + top[0] = top[-1]; + ++top; + goto next; + +print: + std::cout << *--top; + goto next; + +cr: + std::cout << std::endl; + goto next; + +increment: + top[-1]++; + goto next; + +add: + --top; + top[-1] = top[-1] + top[0]; + goto next; + +negate: + top[-1] = -top[-1]; + goto next; + +exit: + std::cout << "Done!" << std::endl; + return 0; +}