-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
51 lines (42 loc) · 1.44 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
import skipSpace from "./skipSpace.js";
function parseApply(expr, program) {
program = skipSpace(program);
if (program[0] != "(") {
return { expr: expr, rest: program };
}
program = skipSpace(program.slice(1));
expr = { type: "apply", operator: expr, args: [] };
while (program[0] != ")") {
let arg = parseExpression(program);
expr.args.push(arg.expr);
program = skipSpace(arg.rest);
if (program[0] == ",") {
program = skipSpace(program.slice(1));
} else if (program[0] != ")") {
throw new SyntaxError("Ожидается ',' или ')'");
}
}
return parseApply(expr, program.slice(1));
}
function parseExpression(program) {
program = skipSpace(program);
let match, expr;
if ((match = /^["']([^"']*)["']/.exec(program))) {
expr = { type: "value", value: match[1] };
} else if ((match = /^\d+\b/.exec(program))) {
expr = { type: "value", value: Number(match[0]) };
} else if ((match = /^[^\s(),#"]+/.exec(program))) {
expr = { type: "word", name: match[0] };
} else {
throw new SyntaxError("Неожиданный синтаксис: " + program);
}
return parseApply(expr, program.slice(match[0].length));
}
function parse(program) {
let { expr, rest } = parseExpression(program);
if (skipSpace(rest).length > 0) {
throw new Error("Неожиданный текст после программы");
}
return expr;
}
export { parse, parseExpression, parseApply };