examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

token-threaded-forth.cpp (938B)


      1 #include <cstdint>
      2 #include <iostream>
      3 
      4 #define LITERAL(x) DOLIT, x
      5 
      6 enum : unsigned char
      7 {
      8 	EXIT,
      9 	DOLIT,
     10 	DUP,
     11 	PRINT,
     12 	CR,
     13 	ADD,
     14 	NEGATE,
     15 	INCREMENT,
     16 };
     17 
     18 int main()
     19 {
     20 	void const* const tokens[] =
     21 	{
     22 		&&exit,
     23 		&&dolit,
     24 		&&dup,
     25 		&&print,
     26 		&&cr,
     27 		&&add,
     28 		&&negate,
     29 		&&increment,
     30 	};
     31 	unsigned char const code[] =
     32 	{
     33 		LITERAL(6),
     34 		DUP,
     35 		PRINT,
     36 		CR,
     37 
     38 		LITERAL(101),
     39 		DUP,
     40 		PRINT,
     41 		CR,
     42 
     43 		ADD,
     44 		PRINT,
     45 		CR,
     46 
     47 		EXIT,
     48 	};
     49 	std::intptr_t stack[1024];
     50 
     51 	std::intptr_t* top = stack;
     52 	unsigned char const* instruction = code;
     53 
     54 next:
     55 	goto *tokens[*instruction++];
     56 
     57 dolit:
     58 	*top++ = *instruction++;
     59 	goto next;
     60 
     61 dup:
     62 	top[0] = top[-1];
     63 	++top;
     64 	goto next;
     65 
     66 print:
     67 	std::cout << *--top;
     68 	goto next;
     69 
     70 cr:
     71 	std::cout << std::endl;
     72 	goto next;
     73 
     74 increment:
     75 	top[-1]++;
     76 	goto next;
     77 
     78 add:
     79 	--top;
     80 	top[-1] = top[-1] + top[0];
     81 	goto next;
     82 
     83 negate:
     84 	top[-1] = -top[-1];
     85 	goto next;
     86 
     87 exit:
     88 	std::cout << "Done!" << std::endl;
     89 	return 0;
     90 }