-
Notifications
You must be signed in to change notification settings - Fork 1
/
tokens.ts
140 lines (110 loc) · 2.25 KB
/
tokens.ts
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
export const enum Tokens {
NAME,
ASSIGNMENT,
NUMBER,
// Operators
OPERATOR_ADD,
OPERATOR_SUBTRACT,
// Punctuation
PAREN_LEFT,
PAREN_RIGHT,
COMMA,
BRACE_LEFT,
BRACE_RIGHT,
}
const SPECIAL_CHAR_MAP: Record<string, Tokens> = {
"(": Tokens.PAREN_LEFT,
")": Tokens.PAREN_RIGHT,
",": Tokens.COMMA,
"{": Tokens.BRACE_LEFT,
"}": Tokens.BRACE_RIGHT,
};
const specialCharMapKeys = Object.keys(SPECIAL_CHAR_MAP);
export interface Token {
type: Tokens;
value?: string;
}
function tokenizeLine(contents: string, lineNr: number) {
const tokens: Token[] = [];
let cursor = 0;
while (cursor < contents.length) {
let char = contents[cursor];
if (char === "-") {
cursor++;
tokens.push({type: Tokens.OPERATOR_SUBTRACT});
continue;
}
if (char === "+") {
cursor++;
tokens.push({type: Tokens.OPERATOR_ADD});
continue;
}
if (specialCharMapKeys.includes(char)) {
tokens.push({type: SPECIAL_CHAR_MAP[char]});
cursor++;
continue;
}
if (char === "/") {
const peek = contents[cursor + 1];
// A comment
if (peek === "/") {
return tokens;
}
}
if (char === "=") {
const peek = contents[cursor + 1];
switch (true) {
case peek === "=": {
// evaluation
break;
}
default: {
tokens.push({type: Tokens.ASSIGNMENT, value: "="});
cursor++;
continue;
}
}
}
if (/\s/.test(char)) {
cursor++;
continue;
}
const numbers = /[0-9]/;
if (numbers.test(char)) {
let value = "";
while (numbers.test(char)) {
value += char;
char = contents[++cursor];
}
tokens.push({
type: Tokens.NUMBER,
value,
});
continue;
}
const letters = /[a-z_]/i;
if (letters.test(char)) {
let value = "";
while (char && letters.test(char)) {
value += char;
char = contents[++cursor];
}
tokens.push({type: Tokens.NAME, value});
continue;
}
throw new TypeError(
`stupid baka syntax error at ${char} on line ${lineNr}`
);
}
return tokens;
}
export function parse(file: string) {
const lines = file.split("\n");
const tokens: Token[] = [];
for (let line = 1; line <= lines.length; line++) {
const contents = lines[line - 1];
const lineTokens = tokenizeLine(contents, line);
tokens.push(...lineTokens);
}
return tokens;
}