/
buildGrammar.js
238 lines (211 loc) · 7.38 KB
/
buildGrammar.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import ohmGrammar from '../dist/ohm-grammar.js';
import {Builder} from './Builder.js';
import * as common from './common.js';
import * as errors from './errors.js';
import {Grammar} from './Grammar.js';
import * as pexprs from './pexprs.js';
const superSplicePlaceholder = Object.create(pexprs.PExpr.prototype);
function namespaceHas(ns, name) {
// Look for an enumerable property, anywhere in the prototype chain.
for (const prop in ns) {
if (prop === name) return true;
}
return false;
}
// Returns a Grammar instance (i.e., an object with a `match` method) for
// `tree`, which is the concrete syntax tree of a user-written grammar.
// The grammar will be assigned into `namespace` under the name of the grammar
// as specified in the source.
export function buildGrammar(match, namespace, optOhmGrammarForTesting) {
const builder = new Builder();
let decl;
let currentRuleName;
let currentRuleFormals;
let overriding = false;
const metaGrammar = optOhmGrammarForTesting || ohmGrammar;
// A visitor that produces a Grammar instance from the CST.
const helpers = metaGrammar.createSemantics().addOperation('visit', {
Grammars(grammarIter) {
return grammarIter.children.map(c => c.visit());
},
Grammar(id, s, _open, rules, _close) {
const grammarName = id.visit();
decl = builder.newGrammar(grammarName);
s.child(0) && s.child(0).visit();
rules.children.map(c => c.visit());
const g = decl.build();
g.source = this.source.trimmed();
if (namespaceHas(namespace, grammarName)) {
throw errors.duplicateGrammarDeclaration(g, namespace);
}
namespace[grammarName] = g;
return g;
},
SuperGrammar(_, n) {
const superGrammarName = n.visit();
if (superGrammarName === 'null') {
decl.withSuperGrammar(null);
} else {
if (!namespace || !namespaceHas(namespace, superGrammarName)) {
throw errors.undeclaredGrammar(superGrammarName, namespace, n.source);
}
decl.withSuperGrammar(namespace[superGrammarName]);
}
},
Rule_define(n, fs, d, _, b) {
currentRuleName = n.visit();
currentRuleFormals = fs.children.map(c => c.visit())[0] || [];
// If there is no default start rule yet, set it now. This must be done before visiting
// the body, because it might contain an inline rule definition.
if (!decl.defaultStartRule && decl.ensureSuperGrammar() !== Grammar.ProtoBuiltInRules) {
decl.withDefaultStartRule(currentRuleName);
}
const body = b.visit();
const description = d.children.map(c => c.visit())[0];
const source = this.source.trimmed();
return decl.define(currentRuleName, currentRuleFormals, body, description, source);
},
Rule_override(n, fs, _, b) {
currentRuleName = n.visit();
currentRuleFormals = fs.children.map(c => c.visit())[0] || [];
const source = this.source.trimmed();
decl.ensureSuperGrammarRuleForOverriding(currentRuleName, source);
overriding = true;
const body = b.visit();
overriding = false;
return decl.override(currentRuleName, currentRuleFormals, body, null, source);
},
Rule_extend(n, fs, _, b) {
currentRuleName = n.visit();
currentRuleFormals = fs.children.map(c => c.visit())[0] || [];
const body = b.visit();
const source = this.source.trimmed();
return decl.extend(currentRuleName, currentRuleFormals, body, null, source);
},
RuleBody(_, terms) {
return builder.alt(...terms.visit()).withSource(this.source);
},
OverrideRuleBody(_, terms) {
const args = terms.visit();
// Check if the super-splice operator (`...`) appears in the terms.
const expansionPos = args.indexOf(superSplicePlaceholder);
if (expansionPos >= 0) {
const beforeTerms = args.slice(0, expansionPos);
const afterTerms = args.slice(expansionPos + 1);
// Ensure it appears no more than once.
afterTerms.forEach(t => {
if (t === superSplicePlaceholder) throw errors.multipleSuperSplices(t);
});
return new pexprs.Splice(
decl.superGrammar,
currentRuleName,
beforeTerms,
afterTerms,
).withSource(this.source);
} else {
return builder.alt(...args).withSource(this.source);
}
},
Formals(opointy, fs, cpointy) {
return fs.visit();
},
Params(opointy, ps, cpointy) {
return ps.visit();
},
Alt(seqs) {
return builder.alt(...seqs.visit()).withSource(this.source);
},
TopLevelTerm_inline(b, n) {
const inlineRuleName = currentRuleName + '_' + n.visit();
const body = b.visit();
const source = this.source.trimmed();
const isNewRuleDeclaration = !(
decl.superGrammar && decl.superGrammar.rules[inlineRuleName]
);
if (overriding && !isNewRuleDeclaration) {
decl.override(inlineRuleName, currentRuleFormals, body, null, source);
} else {
decl.define(inlineRuleName, currentRuleFormals, body, null, source);
}
const params = currentRuleFormals.map(formal => builder.app(formal));
return builder.app(inlineRuleName, params).withSource(body.source);
},
OverrideTopLevelTerm_superSplice(_) {
return superSplicePlaceholder;
},
Seq(expr) {
return builder.seq(...expr.children.map(c => c.visit())).withSource(this.source);
},
Iter_star(x, _) {
return builder.star(x.visit()).withSource(this.source);
},
Iter_plus(x, _) {
return builder.plus(x.visit()).withSource(this.source);
},
Iter_opt(x, _) {
return builder.opt(x.visit()).withSource(this.source);
},
Pred_not(_, x) {
return builder.not(x.visit()).withSource(this.source);
},
Pred_lookahead(_, x) {
return builder.lookahead(x.visit()).withSource(this.source);
},
Lex_lex(_, x) {
return builder.lex(x.visit()).withSource(this.source);
},
Base_application(rule, ps) {
const params = ps.children.map(c => c.visit())[0] || [];
return builder.app(rule.visit(), params).withSource(this.source);
},
Base_range(from, _, to) {
return builder.range(from.visit(), to.visit()).withSource(this.source);
},
Base_terminal(expr) {
return builder.terminal(expr.visit()).withSource(this.source);
},
Base_paren(open, x, close) {
return x.visit();
},
ruleDescr(open, t, close) {
return t.visit();
},
ruleDescrText(_) {
return this.sourceString.trim();
},
caseName(_, space1, n, space2, end) {
return n.visit();
},
name(first, rest) {
return this.sourceString;
},
nameFirst(expr) {},
nameRest(expr) {},
terminal(open, cs, close) {
return cs.children.map(c => c.visit()).join('');
},
oneCharTerminal(open, c, close) {
return c.visit();
},
escapeChar(c) {
try {
return common.unescapeCodePoint(this.sourceString);
} catch (err) {
if (err instanceof RangeError && err.message.startsWith('Invalid code point ')) {
throw errors.invalidCodePoint(c);
}
throw err; // Rethrow
}
},
NonemptyListOf(x, _, xs) {
return [x.visit()].concat(xs.children.map(c => c.visit()));
},
EmptyListOf() {
return [];
},
_terminal() {
return this.sourceString;
},
});
return helpers(match).visit();
}