Browse Source

Added basic AST traversal compiler!

remotes/origin/HEAD
Seth Stubbs 6 months ago
parent
commit
78bd44be88
  1. 2
      Makefile
  2. 4
      out.tal
  3. 4
      src/main.c
  4. 29
      src/uasm.c
  5. 4
      src/uparse.c
  6. 2
      src/uparse.h

2
Makefile

@ -6,10 +6,12 @@ OUT=bin/uxncle
CHDR=\
src/ulex.h\
src/uparse.h\
src/uasm.h\
CSRC=\
src/ulex.c\
src/uparse.c\
src/uasm.c\
src/main.c
COBJ=$(CSRC:.c=.o)

4
out.tal

@ -0,0 +1,4 @@
|0100
#02 #04 MUL
#06 ADD
BRK

4
src/main.c

@ -1,7 +1,9 @@
#include "uparse.h"
#include "uasm.h"
int main() {
UP_parseSource("5 + 3 * 2");
UASTNode *tree = UP_parseSource("2 * 4 + 6");
UA_genTal(tree, fopen("out.tal", "w"));
return 0;
}

29
src/uasm.c

@ -1,18 +1,41 @@
#include "uasm.h"
static const char preamble[] =
"|10 @Console [ &pad $8 &char ]\n"
"|0100\n";
static const char postamble[] =
"BRK";
void writeLit(FILE *out, int lit) {
fprintf(out, "#%.2x ", lit);
}
void compileAST(FILE *out, UASTNode *node) {
/* first, traverse down the AST recusively */
if (node->left)
compileAST(out, node->left);
if (node->right)
compileAST(out, node->right);
switch(node->type) {
case NODE_ADD: fwrite("ADD\n", 4, 1, out); break;
case NODE_SUB: fwrite("SUB\n", 4, 1, out); break;
case NODE_MUL: fwrite("MUL\n", 4, 1, out); break;
case NODE_DIV: fwrite("DIV\n", 4, 1, out); break;
case NODE_INTLIT: writeLit(out, node->num); break;
default:
printf("Compiler error! unknown AST node!! [%d]\n", node->type);
exit(0);
}
}
void UA_genTal(UASTNode *tree, FILE *out) {
/* first, write the preamble */
fwrite(preamble, sizeof(preamble), 1, out);
fwrite(preamble, sizeof(preamble)-1, 1, out);
/* now parse the whole AST */
compileAST(out, tree);
/* finally, write the postamble */
fwrite(postamble, sizeof(postamble), 1, out);
fwrite(postamble, sizeof(postamble)-1, 1, out);
}

4
src/uparse.c

@ -46,7 +46,7 @@ UASTNode *newNode(UParseState *state, UASTNodeType type, UASTNode *left, UASTNod
}
UASTNode *newNumNode(UParseState *state, UASTNode *left, UASTNode *right, int num) {
UASTNode *node = newNode(state, NODE_NUM, left, right);
UASTNode *node = newNode(state, NODE_INTLIT, left, right);
node->num = num;
return node;
@ -185,7 +185,7 @@ void printNode(UASTNode *node) {
case NODE_SUB: printf("SUB"); break;
case NODE_MUL: printf("MUL"); break;
case NODE_DIV: printf("DIV"); break;
case NODE_NUM: printf("[%d]", node->num); break;
case NODE_INTLIT: printf("[%d]", node->num); break;
default: break;
}
}

2
src/uparse.h

@ -8,7 +8,7 @@ typedef enum {
NODE_SUB,
NODE_MUL,
NODE_DIV,
NODE_NUM
NODE_INTLIT
} UASTNodeType;
typedef struct s_UASTNode {

Loading…
Cancel
Save