-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.js
50 lines (44 loc) · 1.28 KB
/
parse.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
"use strict";
// x -> ["var", "x"]
// (\x M) -> ["lam", "x", M]
// (M N) -> ["app", M, N]
function tokens(line) {
return line.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').trim().split(/\s+/);
}
function parseOne(toks) {
var tok = toks.shift();
if (tok == '(') {
var tmp = /^[\\λ\/]/.test(toks[0])
? ["lam", toks.shift().substr(1), parseOne(toks)]
: ["app", parseOne(toks), parseOne(toks)];
if (toks.shift() != ')') { throw "no matching ')'"; }
return tmp;
} else if (tok == ')') {
throw "bad ')'";
} else {
return ["var", tok];
}
}
function parse(line) { return parseOne(tokens(line)); }
function unparse(exp) {
if (exp[0] == "var") return exp[1];
if (exp[0] == "lam") return `(λ${exp[1]} ${unparse(exp[2])})`;
return `(${unparse(exp[1])} ${unparse(exp[2])})`;
}
function parseFile(path) {
var lines = require("fs").readFileSync(path) + "";
return parse(lines.replace(/(#.*)?\n/g, " "));
}
// TODO: es6 import
exports.parse = parse;
exports.unparse = unparse;
exports.parseFile = parseFile;
/*
function show(line) { console.log(JSON.stringify(parse(line))); }
show("x");
show("(\\x y)");
show("((\\y z)(\\x y))");
show("((λy z)(λx y))");
show("((/y z)(/x y))");
console.log(unparse(parse("((/y z)(/x y))")));
*/