Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Yet another one-page toy interpretter

147 views
Skip to first unread message

luser- -droog

unread,
Jan 14, 2011, 12:23:38 AM1/14/11
to
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[i]; } ) \
_(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] ]);
*/
++i;
ftab[ m[i-1] ]();

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

return 0;
}

0 new messages