diff options
author | Bobby Bingham <koorogi@koorogi.info> | 2017-01-18 18:17:56 -0600 |
---|---|---|
committer | Bobby Bingham <koorogi@koorogi.info> | 2017-01-18 18:23:19 -0600 |
commit | 17d11b2e0af9cbbe9e2c02c4d1a3d2cb4509701e (patch) | |
tree | 16c544f177bf51628da4505ba9383171058ca226 | |
parent | 9244eacb5ab0b9a11480d1ad40d4720575676877 (diff) |
nqasm: store instructions in memory before assembling
-rw-r--r-- | nqasm.c | 53 |
1 files changed, 37 insertions, 16 deletions
@@ -13,27 +13,43 @@ struct label { uint16_t addr; }; -static struct labels { - struct vector v; - struct label l[]; -} *labels; - uint16_t addr; -static int labels_init(void) -{ - return !(labels = vector_init(8, sizeof labels->l[0], sizeof *labels)); -} +#define DEFINE_VECTOR(name, arraytype, arrayname, initsize) \ + static struct name { \ + struct vector v; \ + arraytype arrayname[]; \ + } *name; \ + \ + static int name ## _init(void) \ + { \ + return !(name = vector_init(initsize, sizeof (arraytype), sizeof *name)); \ + } \ + \ + static arraytype *name ## _append(void) \ + { \ + struct vector *v = &name->v; \ + arraytype *e = vector_append(&v); \ + name = (struct name *)v; \ + return e; \ + } -static struct label *labels_append(void) +DEFINE_VECTOR(labels, struct label, l, 8) +DEFINE_VECTOR(instrs, struct instruction, i, 256) + +void add_instruction(const struct instruction *inst) { - struct vector *v = &labels->v; - struct label *l = vector_append(&v); - labels = (struct labels *)v; - return l; + struct instruction *i = instrs_append(); + if (!i) { + fprintf(stderr, "unable to allocate instruction\n"); + exit(1); + } + + *i = *inst; + addr += 2; } -void add_instruction(const struct instruction *inst) +static void assemble_instruction(const struct instruction *inst) { const struct mnemonic *mnem = &mnemonics[inst->mnem]; uint16_t bits = mnem->bits; @@ -45,7 +61,6 @@ void add_instruction(const struct instruction *inst) } printf("%04x\n", bits); - addr += 2; } void add_label(const char *name) @@ -65,8 +80,14 @@ void add_label(const char *name) int main(int argc, char **argv) { labels_init(); + instrs_init(); yyparse(); + + for (size_t i = 0; i < instrs->v.count; i++) { + assemble_instruction(instrs->i + i); + } + return 0; } |