Yet another one-page toy interpretter


L

luser- -droog

Does this constitute abuse of macros?

/* Token-Threaded-Code Virtual Machine */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

#define size(a) (sizeof a/sizeof*a)

typedef int16_t cell;
cell lopad[10];
cell m[10000]; /* memory */
cell hipad[10];
cell w; /* work */
cell i; /* instruction */
cell s = 0; /* parameter stack grows up */
cell r = size(m)-1; /* return stack grows down */
cell ss; /* stack segment */

#define OPS(_) \
_(zero, { w = 0; } ) \
_(push, { m[ss+s++] = w; } ) \
_(pop, { w = m[--s+ss]; } ) \
_(add, { w += m[--s+ss]; } ) \
_(sub, { w -= m[--s+ss]; } ) \
_(print, { printf("%hu\n", w); } ) \
_(call, { m[r--] = i; \
i = m; } ) \
_(jump, { i = w; } ) \
_(ret, { i = m[++r]; } ) \
_(quit, { exit(w); } ) \

#define VFUN(a, b) \
void a (void) b
OPS(VFUN)
void noop (void) { } /* noop is 'no operation' AND 'no. of operators'
*/

void (*ftab[])(void) = {
#define RFUN(a, b) \
a ,
OPS(RFUN) noop /* noop brackets the otherwise trailing comma */
};

enum opcode {
#define EFUN(a, b) \
op_ ## a ,
OPS(EFUN) op_noop /* noop brackets the otherwise trailing comma */
};

char *stab[] = {
#define SFUN(a, b) \
#a ,
OPS(SFUN) "noop"
};

int main (int argc, char **argv) {

w = 0; jump(); /* start of program */
m[w++] = op_call;
m[w++] = 10;
m[w++] = op_quit;

w = 10; /* double procedure */
m[w++] = op_push;
m[w++] = op_add;
m[w++] = op_print;
m[w++] = op_ret;

ss = 20; /* put stack above program */

w = 5; /* initial value */

do {
/*
printf("%s\n", stab[ m ]);
*/
++i;
ftab[ m[i-1] ]();

if ( (s < 0)
|| (r > size(m)-1)
|| (s == r)
)
{
fprintf(stderr, "ERROR\n");
exit(1);
}
} while(1);

return 0;
}
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top