-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.js
71 lines (52 loc) · 1.31 KB
/
parser.js
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
module.exports = function (program) {
const tokens = [];
const length = program.length;
let line = 1;
let character = 1;
const locations = [];
for (let i = 0, starts = 0, ends = 0; i < length; i++) {
const c = program[i];
if (c === '\n') {
++line;
character = 1;
continue;
}
if ([ '+', '-', '<', '>', ',', '.', '[', ']', ].indexOf(c) > -1) {
const token = {
character,
line,
type: c,
};
if (c === '[') {
++starts;
locations.push({
character,
line,
tokenId: tokens.length,
});
}
if (c === ']') {
++ends;
if (starts < ends) {
throw new SyntaxError(
`An unmatched ] command was found at line ${line}, character ${character}.
You can't close a loop without opening one!`
);
}
const { tokenId, } = locations.pop();
token.start = tokenId;
tokens[tokenId].end = tokens.length;
}
tokens.push(token);
}
++character;
}
if (locations.length) {
const { line, character, } = locations.shift();
throw new SyntaxError(
`An unmatched [ was found at line ${line}, character ${character}.
Don't forget to close your loops!`
);
}
return tokens;
};