Skip to content

Instantly share code, notes, and snippets.

@startling
Forked from magcius/opcodes.c
Created March 16, 2012 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save startling/2048783 to your computer and use it in GitHub Desktop.
Save startling/2048783 to your computer and use it in GitHub Desktop.
#include <glib.h>
typedef struct {
GSList *stack;
} MachineState;
static void machine_push (MachineState *state, int v);
static int machine_pop (MachineState *state);
/* pushes an operand onto the operand stack */
static void
op_pushint (MachineState *state,
int v)
{
machine_push (state, v);
}
static void
op_add (MachineState *state)
{
int a, b, res;
a = machine_pop (state);
b = machine_pop (state);
res = a + b;
machine_push (state, res);
}
static void
op_sub (MachineState *state)
{
int a, b, res;
a = machine_pop (state);
b = machine_pop (state);
res = a - b;
machine_push (state, res);
}
static void
op_mul (MachineState *state)
{
int a, b, res;
a = machine_pop (state);
b = machine_pop (state);
res = a * b;
machine_push (state, res);
}
G_GNUC_UNUSED
static void
op_pop (MachineState *state)
{
machine_pop (state);
}
G_GNUC_UNUSED
static void
op_dup (MachineState *state)
{
int a;
a = machine_pop (state);
machine_push (state, a);
machine_push (state, a);
}
static void
op_swap (MachineState *state)
{
int a, b;
a = machine_pop (state);
b = machine_pop (state);
machine_push (state, a);
machine_push (state, b);
}
static void
op_print (MachineState *state)
{
int a;
a = machine_pop (state);
g_print ("%d\n", a);
}
int
main (int argc, char **argv)
{
MachineState state;
state.stack = NULL;
/* (5 * (2 + 4)) - 3 */
op_pushint (&state, 5);
op_pushint (&state, 2);
op_pushint (&state, 4);
op_add (&state);
op_mul (&state);
op_pushint (&state, 3);
op_swap (&state);
op_sub (&state);
op_print (&state);
return 0;
}
static void
machine_push (MachineState *state,
int v)
{
state->stack = g_slist_prepend (state->stack, GINT_TO_POINTER (v));
}
static int
machine_pop (MachineState *state)
{
int v;
v = GPOINTER_TO_INT (state->stack->data);
state->stack = g_slist_delete_link (state->stack, state->stack);
return v;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment