-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompiler.c
88 lines (70 loc) · 1.45 KB
/
compiler.c
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
79
80
81
82
83
84
85
86
87
88
#include <stdlib.h>
#include "scanner.h"
#include "chunk.h"
#include "value.h"
#include "common.h"
typedef struct {
Token previous;
Token current;
bool hadError;
} Parser;
Parser parser;
Chunk* compilingChunk;
static Chunk* currentChunk() {
return compilingChunk;
}
static void emitByte(int byte) {
uint8_t ubyte = (uint8_t)byte;
writeChunk(currentChunk(), ubyte);
}
static void emitConstant(Value value) {
emitByte(OP_CONSTANT);
int constant = addConstant(currentChunk(), value);
emitByte(constant);
}
static void advance() {
parser.previous = parser.current;
for (;;) {
parser.current = scanToken();
if (parser.current.type != TOKEN_ERROR) break;
}
}
static bool check(TokenType type) {
return parser.current.type == type;
}
static bool match(TokenType type) {
if (!check(type)) return false;
advance();
return true;
}
static void consume(TokenType type) {
if (parser.current.type == type) {
advance();
return;
}
}
static void printStatement() {
advance();
int value = atoi(parser.previous.start);
emitConstant(value);
consume(TOKEN_SEMICOLON);
emitByte(OP_PRINT);
}
static void declaration() {
if (match(TOKEN_PRINT)) {\
printStatement();
}
}
static void endCompiler() {
emitByte(OP_RETURN);
}
int compile(const char* source, Chunk* chunk) {
initScanner(source);
compilingChunk = chunk;
advance();
while (!match(TOKEN_EOF)) {
declaration();
}
endCompiler();
return 0;
}