Browse Source

codegen away

master
Yuki Izumi 4 years ago
parent
commit
3418e02130
No known key found for this signature in database GPG Key ID: 44A3D2C95E26BB14
5 changed files with 92 additions and 7 deletions
  1. +0
    -1
      .gitignore
  2. +0
    -2
      lc/cfuhash.c
  3. +86
    -3
      lc/codegen.c
  4. BIN
      out.o
  5. +6
    -1
      vm/main.c

+ 0
- 1
.gitignore View File

@@ -1,2 +1 @@
/build
*.o

+ 0
- 2
lc/cfuhash.c View File

@@ -812,8 +812,6 @@ typedef struct _pretty_print_arg {
static int
_pretty_print_foreach(void *key, size_t key_size, void *data, size_t data_size, void *arg) {
_pretty_print_arg *parg = (_pretty_print_arg *)arg;
key_size = key_size;
data_size = data_size;
parg->count += fprintf(parg->fp, "\t\"%s\" => \"%s\",\n", (char *)key, (char *)data);
return 0;
}


+ 86
- 3
lc/codegen.c View File

@@ -1,16 +1,99 @@
#include <stdlib.h>
#include "codegen.h"
#include "cfuhash.h"

enum {
NOP,
LDu8,
LDu32,
ADD,
LOCAL,
ENDLOCAL,
STOu8,
RCu8,
DROP,
RET = 0xFF,
};

static void put8(FILE *f, uint8_t n) {
fputc(n, f);
}

static cfuhash_table_t *vars;

void emit(FILE *f, expr const *e) {
switch (e->type) {
case E_IMM_U8:
put8(f, LDu8);
put8(f, e->as.imm_u8);
break;
case E_ASSIGN: {
emit(f, e->as.assign.rhs);
put8(f, STOu8);
void *ix;
cfuhash_get_data(vars, e->as.assign.lhs, -1, &ix, NULL);
put8(f, (uint8_t) ix);
break;
}
case E_REF: {
put8(f, RCu8);
void *ix;
cfuhash_get_data(vars, e->as.ref, -1, &ix, NULL);
put8(f, (uint8_t) ix);
break;
}
case E_BINOP: {
emit(f, e->as.binop.lhs);
emit(f, e->as.binop.rhs);
put8(f, ADD);
break;
}
default:
abort();
}
}

void codegen(FILE *f, ast const *ast) {
// scan function for variable assignments
cfuhash_table_t *vars = cfuhash_new();
vars = cfuhash_new();

for (expr_list *it = ast->start; it; it = it->next) {
uint8_t i = 0;
for (expr_list const *it = ast->start; it; it = it->next) {
expr const *e = it->expr;
if (e->type == E_ASSIGN) {
cfuhash_put_data(vars, e->as.assign.lhs, -1, NULL, 0, NULL);
if (!cfuhash_exists_data(vars, e->as.assign.lhs, -1)) {
cfuhash_put_data(vars, e->as.assign.lhs, -1, (void *) (intptr_t) i, 0, NULL);
++i;
}
}
}

size_t num_keys;
void **keys = cfuhash_keys_data(vars, &num_keys, NULL, 1);
for (size_t i = 0; i < num_keys; ++i)
printf("key: %s\n", keys[i]);
free(keys);

if (num_keys > 255)
abort();

// emit

if (num_keys) {
put8(f, LOCAL);
put8(f, num_keys);
}

for (expr_list const *it = ast->start; it; it = it->next) {
emit(f, it->expr);
if (it != ast->end)
put8(f, DROP);
}

if (num_keys)
put8(f, ENDLOCAL);

put8(f, RET);

cfuhash_destroy(vars);
}

BIN
out.o View File


+ 6
- 1
vm/main.c View File

@@ -279,7 +279,12 @@ static int step(vm_process *p) {
// RC u8
uint8_t n = read8(p);
p->stack = make_stack(p->stack, copy(p->local->v[n]));
break;
break;
}
case 0x08: {
// DROP
free_value(pop_stack(p));
break;
}
case 0xFF:
// RET


Loading…
Cancel
Save