-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.c
executable file
·108 lines (84 loc) · 2.43 KB
/
parser.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#include "parser.h"
/*
void initParser(Parser* parser, Scanner* scanner) {
parser->scanner = scanner;
parser->hadError = false;
parser->panicMode = false;
}
void errorAt(Parser* parser, Token* token, const char* message) {
if (parser->panicMode) return;
parser->panicMode = true;
fprintf(stderr, "[ line %d ] Error", token->line);
if (token->type == TOKEN_EOF) {
fprintf(stderr, " at end");
}
else if (token->type == TOKEN_ERROR) {
// nothing
}
else {
fprintf(stderr, " at '%.*s'", token->length, token->start);
}
fprintf(stderr, ": %s\n", message);
parser->hadError = true;
}
void errorAtPrev(Parser* parser, const char* msg) {
errorAt(parser, &parser->previous, msg);
}
void errorAtCrnt(Parser* parser, const char* msg) {
errorAt(parser, &parser->current, msg);
}
void advance(Parser* parser) {
parser->previous = parser->current;
parser->current = parser->next;
for (;;) {
parser->next = scanToken(parser->scanner);
if (parser->next.type != TOKEN_ERROR) break;
errorAtCrnt(parser, parser->next.start);
}
}
bool checkNext(Parser* parser, TokenType type) {
return parser->next.type == type;
}
bool check(Parser* parser, TokenType type) {
return parser->current.type == type;
}
bool match(Parser* parser, TokenType type) {
if (!check(parser, type)) return false;
advance(parser);
return true;
}
void consume(Parser* parser, TokenType type, const char* msg) {
if (check(parser, type)) {
advance(parser);
return;
}
errorAtCrnt(parser, msg);
}
void end(Parser* parser) {
if (check(parser, TOKEN_BREAK) || check(parser, TOKEN_SEMICOLON) || check(parser, TOKEN_EOF)) {
advance(parser);
return;
}
errorAtCrnt(parser, "Expected newline or ';'");
}
bool isAtBreak(Parser* parser) {
return check(parser, TOKEN_BREAK) || check(parser, TOKEN_SEMICOLON) || check(parser, TOKEN_EOF);
}
void synchronise(Parser* parser) {
parser->panicMode = false;
while (parser->current.type != TOKEN_EOF) {
if (parser->previous.type == TOKEN_BREAK || parser->previous.type == TOKEN_SEMICOLON) return;
switch (parser->current.type) {
case TOKEN_PRINT:
case TOKEN_RETURN:
return;
default:
// do nothing
}
advance(parser);
}
}
*/