summaryrefslogtreecommitdiff
path: root/com.c
blob: b97ffc02336f588302eefddf7a5030d28cef28c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "vm.h"
#include "ast.h"
#include "read.h"
#include "state.h"

static void compile_node(State *S, Chunk *ch, AstNode a) {
	switch (a.ty) {
	case AST_IDENT:
		printf("can't compile ident\n");
		exit(1);
		break;
	case AST_NUM:
		chunk_wbc(S, ch, OP_LOADK);
		chunk_wbc(S, ch, chunk_wconst(S, ch, VAL_NUM(a.as.num)));
		break;
	case AST_STRING: {
		size_t len = strlen(a.as.str);
		ObjString *o = objstring_copy(S, a.as.str, len);
		chunk_wbc(S, ch, OP_LOADK);
		chunk_wbc(S, ch, chunk_wconst(S, ch, VAL_OBJ(o)));
		break;
	}
	case AST_LIST: {
		AstVec l = a.as.list;
		#define CK(cond, msg) if (!(cond)) { puts(msg); exit(1); }
		CK(l.vals[0].ty == AST_IDENT, "can only call ops");

		if (0 == strcmp(l.vals[0].as.str, "print")) {
			CK(l.len == 2, "print requires exactly 1 argument");
			compile_node(S, ch, l.vals[1]);
			chunk_wbc(S, ch, OP_PRINT);
			break;
		}
		CK(l.len == 3, "can only compile binary ops");
		char opchar = l.vals[0].as.str[0];
		Op op;
		switch (opchar) {
		#define OP(char, code) case char: op = code; break;
			OP('+', OP_ADD)
			OP('-', OP_SUB)
			OP('*', OP_MUL)
			OP('/', OP_DIV)
		#undef OP
			default:
				printf("unkown op %s\n",l.vals[0].as.str);
				exit(1);
				break;
		}
		compile_node(S, ch, l.vals[1]);
		compile_node(S, ch, l.vals[2]);
		chunk_wbc(S, ch, op);
		#undef CK
	}
	}
}


int main() {
	State st = state_new();
	State *S = &st;
	Thread th = thread_new(S);
	st.th = &th;
	Chunk ch = chunk_new(S);
	th.ch = &ch;

	AstNode an = read();
	compile_node(S, &ch, an);

	chunk_wbc(S, &ch, OP_PRINT);
	chunk_wbc(S, &ch, OP_RET);

	runvm(S);
}