/
pexprs-introduceParams.js
68 lines (59 loc) · 2.1 KB
/
pexprs-introduceParams.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
'use strict';
// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------
const common = require('./common');
const pexprs = require('./pexprs-main');
// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------
/*
Called at grammar creation time to rewrite a rule body, replacing each reference to a formal
parameter with a `Param` node. Returns a PExpr -- either a new one, or the original one if
it was modified in place.
*/
pexprs.PExpr.prototype.introduceParams = common.abstract('introduceParams');
pexprs.any.introduceParams =
pexprs.end.introduceParams =
pexprs.Terminal.prototype.introduceParams =
pexprs.Range.prototype.introduceParams =
pexprs.Param.prototype.introduceParams =
pexprs.UnicodeChar.prototype.introduceParams =
function(formals) {
return this;
};
pexprs.Alt.prototype.introduceParams = function(formals) {
this.terms.forEach((term, idx, terms) => {
terms[idx] = term.introduceParams(formals);
});
return this;
};
pexprs.Seq.prototype.introduceParams = function(formals) {
this.factors.forEach((factor, idx, factors) => {
factors[idx] = factor.introduceParams(formals);
});
return this;
};
pexprs.Iter.prototype.introduceParams =
pexprs.Not.prototype.introduceParams =
pexprs.Lookahead.prototype.introduceParams =
pexprs.Lex.prototype.introduceParams =
function(formals) {
this.expr = this.expr.introduceParams(formals);
return this;
};
pexprs.Apply.prototype.introduceParams = function(formals) {
const index = formals.indexOf(this.ruleName);
if (index >= 0) {
if (this.args.length > 0) {
// TODO: Should this be supported? See issue #64.
throw new Error('Parameterized rules cannot be passed as arguments to another rule.');
}
return new pexprs.Param(index).withSource(this.source);
} else {
this.args.forEach((arg, idx, args) => {
args[idx] = arg.introduceParams(formals);
});
return this;
}
};