-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
56 lines (48 loc) · 1.46 KB
/
Copy pathparser.js
File metadata and controls
56 lines (48 loc) · 1.46 KB
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
require('util-is');
var util = require('util');
var Expr = require('./expr');
var Parsimmon = require('parsimmon');
var regex = Parsimmon.regex;
var string = Parsimmon.string;
var optWhitespace = Parsimmon.optWhitespace;
var whitespace = Parsimmon.whitespace;
var lazy = Parsimmon.lazy;
var seq = Parsimmon.seq;
function lexeme(p) { return p.skip(optWhitespace); }
var lparen = lexeme(string('('));
var rparen = lexeme(string(')'));
var arrow = lexeme(string('.'));
var fslash = lexeme(string('/'));
var id = lexeme(regex(/[a-z_]\w*/i));
// expr ::= app | non~app
var expr = lazy('expression', function() {
return app.or(nonApp);
});
// pexpr ::= ( expr )
var pexpr = lparen.then(expr).skip(rparen);
// lambda ::= / id . expr
var lambda = seq(fslash, id, arrow, expr).map(function(res) {
return Expr.Lambda(res[1], handleVar(res[3]));
});
// nonApp ::= lambda | id | pexpr
var nonApp = lambda.or(id).or(pexpr);
// app ::= nonApp nonApp
var app = seq(nonApp, nonApp).map(function(res) {
return Expr.App(handleVar(res[0]), handleVar(res[1]));
});
module.exports = function (str) {
var result = expr.parse(str);
if (result.status === true) {
return handleVar(result.value);
} else {
throw new Error('Failed to parse expression [' + result.index
+ '] expected: ' + result.expected);
}
};
// All non function bindings should be converted to variables
function handleVar(e) {
if (util.isString(e)) {
return Expr.Var(e);
}
return e;
}