Yet another one-page toy interpretter

Discussion in 'C Programming' started by luser- -droog, Jan 14, 2011.

  1. 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;
    }
    luser- -droog, Jan 14, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Berehem
    Replies:
    4
    Views:
    536
    Lawrence Kirby
    Apr 28, 2005
  2. Robert Cohen
    Replies:
    3
    Views:
    249
    Andrew Durstewitz
    Jul 15, 2003
  3. Gary Herron
    Replies:
    1
    Views:
    45
    Gary Herron
    Jan 27, 2014
  4. Dave Angel
    Replies:
    4
    Views:
    56
    Mark Lawrence
    Jan 27, 2014
  5. Terry Reedy
    Replies:
    1
    Views:
    45
    Ethan Furman
    Jan 27, 2014
Loading...

Share This Page