forked from alexwarth/ometa-js
/
grammar.js
478 lines (406 loc) · 11.3 KB
/
grammar.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
var ometajs = require('../../ometajs'),
util = require('util');
//
// ### function AbstractGrammar (source)
// #### @source {Array|String} source code
// Abstract Grammar constructor
//
function AbstractGrammar(source) {
ometajs.core.AbstractParser.call(this, source);
this._name = 'AbstractGrammar';
this._errorRule = '';
this._errorOffset = '';
this._errorSource = source;
}
util.inherits(AbstractGrammar, ometajs.core.AbstractParser);
module.exports = AbstractGrammar;
//
// ### function match (source, rule, args)
// #### @source {Array|String} source code
// #### @rule {String} rule to start parsing with
// #### @args {Array} (optional) arguments
// #### @errback {Function} (optional) Error handler
// Creates instance of the grammar, invokes rule and returns a result
//
AbstractGrammar.match = function match(source, rule, args, errback) {
return this.matchAll([source], rule, args, errback);
};
//
// ### function matchAll (source, rule, args)
// #### @source {Array|String} source code
// #### @rule {String} rule to start parsing with
// #### @args {Array} (optional) arguments
// #### @errback {Function} (optional) Error handler
// Creates instance of the grammar, invokes rule and returns a result
//
AbstractGrammar.matchAll = function matchAll(source, rule, args, errback) {
var grmr = new this(source);
if (!grmr._rule(rule, false, args)) {
// Throw errors if no error handler was provided
if (!errback) errback = function (err) { throw err; };
if (grmr._errorOffset >= 0) {
var line,
lineNumber = 0,
offset,
current = 0,
error = grmr._errorStack || new Error();
if (Array.isArray(source)) {
// TODO: Implement me!
} else {
source.split(/\n/g).some(function (source, i) {
if (grmr._errorOffset > (current + source.length + 1)) {
current += source.length + 1;
return false;
}
offset = grmr._errorOffset - current;
line = source;
lineNumber = i;
return true;
});
error.message = grmr._errorRule + ' rule failed at: ' +
lineNumber + ':' + offset + '\n' +
line + '\n' +
new Array(offset + 1).join(' ') + '^';
error.line = lineNumber;
error.offset = line;
}
errback(error);
} else {
errback(new Error('Unexpected negative offset'));
}
return;
}
return grmr._getIntermediate();
};
//
// ### function _lastError (rule)
// #### @rule {String} Rule where we've just failed
// Internal method for tracking errors
//
AbstractGrammar.prototype._lastError = function _lastError(rule) {
if (this._errorOffset <= this._offset) {
this._errorRule = rule;
this._errorOffset = this._offset;
this._errorSource = this._source;
}
};
//
// ### function _invoke (grmr, rule, fn, nc, args)
// #### @grmr {String} name of grammar
// #### @rule {String} Rule's name
// #### @fn {Function} Rule's body
// #### @nc {Boolean} If true - rule will be applied without left-recursion
// #### check.
// #### @args {Array} Arguments to rule
//
AbstractGrammar.prototype._invoke = function _invoke(grmr, rule, fn, nc, args) {
function invoke() {
var body = fn || grmr.prototype[rule];
// Nullify result
this._result = undefined;
// Invoke actual rule function
if (body === undefined) return false;
return body.call(this);
}
if (args && args.length > 0) {
return this._simulate(args, invoke);
} else if (!nc) {
return this._cache(grmr.name, rule, invoke);
} else {
return invoke.call(this);
}
};
//
// ### function rule (name, args)
// #### @name {String} rule name
// #### @args {Array} (optional) arguments
// #### @cons {AbstractGrammar}
// #### @body {Function} rule's body
//
AbstractGrammar.prototype._rule = function rule(name,
nocache,
args,
cons,
body) {
var res = false;
// `apply` is a meta rule that invokes rule provided in arguments
if (name === 'apply') {
res = this._rule(args[0], nocache, args.slice(1));
// Token rule is quite magical :)
// It'll remember a token at the current position
// and then use _tokenCache for matching
// that change will automatically add lexer for any grammar
} else if (name === 'token') {
var flat = this._history.length === 0 && this._type === 'string',
offset = this._offset,
cache;
// This cache will work only on flat string source
// If we hit cache - just do a simple comparison
if (flat && (cache = this._tokenCache[offset]) !== undefined) {
if (cache.token === args[0]) {
this._skip(cache.skip);
this._setIntermediate(cache.value, true);
res = true;
} else {
res = false;
}
} else {
res = this._atomic(function() {
// If not - invoke grammar code first
if (!this._invoke(cons || this.constructor, name, body, nocache)) {
return false;
}
// Get result
var pair = this._getIntermediate();
// And store it cache
if (flat) {
this._tokenCache[offset] = {
token: pair[0],
value: pair[1],
skip: this._offset - offset
};
}
// Anyway perform check
if (pair[0] === args[0]) {
this._setIntermediate(pair[1], true);
return true;
} else {
return false;
}
});
}
} else {
res = this._invoke(cons || this.constructor, name, body, nocache, args);
}
if (!res) {
this._lastError(name);
return false
} else {
return true;
}
};
//
// ### function fromTo (from, to)
// #### @from {any}
// #### @to {any}
// Tries to match content between `from` and `to`
//
AbstractGrammar.prototype._fromTo = function fromTo(from, to) {
var head = this._source.slice(this._offset, this._offset + from.length);
if (head !== from) return false;
var t = this._source.indexOf(to, this._offset);
if (t === -1) return false;
t += to.length;
var value = this._source.slice(this._offset, t);
this._skip(value.length);
this._setIntermediate(value);
return true;
};
//
// ### function seq (str)
// #### @str {String}
// Tries to match chars sequence
//
AbstractGrammar.prototype._seq = function seq(str) {
if (this._type === 'string') {
var len = str.length;
if (len < 4) {
for (var i = 0; i < len; i++) {
if (!this._match(str[i])) return false;
}
} else {
var head = this._source.slice(this._offset, this._offset + len);
if (head !== str) return false;
this._skip(len);
}
} else {
for (var i = 0; i < str.length; i++) {
if (!this._match(str[i])) return false;
}
}
return true;
};
//
// ### function word ()
// Tries to match non-space chars sequence
//
AbstractGrammar.prototype._word = function word() {
if (this._type === 'string') {
var match = this._source.slice(this._offset).match(/^[^\s]+/);
if (match === null) return false;
this._skip(match[0].length);
this._setIntermediate(match[0]);
return true;
} else {
var chars = [],
current;
while (!this._isEnd() && !(/\s/.test(current = this._current()))) {
this._skip();
chars.push(current);
}
if (!this._isEnd()) return false;
this._setIntermediate(chars.join(''));
return true;
}
};
//
// ### function any (fn)
// #### @fn {Function} function to iterate with
// Greedy matcher, count >= 0
//
AbstractGrammar.prototype._any = function any(fn) {
var list = [];
while (!this._isEnd() && fn.call(this)) {
list.push(this._getIntermediate());
}
this._setIntermediate(list);
return true;
};
//
// ### function many (fn)
// #### @fn {Function} function to iterate with
// Greedy matcher, count > 0
//
AbstractGrammar.prototype._many = function many(fn) {
var list = [];
if (!fn.call(this)) return false;
list.push(this._getIntermediate());
while (!this._isEnd() && fn.call(this)) {
list.push(this._getIntermediate());
}
this._setIntermediate(list);
return true;
};
//
// ### function optional (fn)
// #### @fn {Function} function to iterate with
// Match, or at least not fail
//
AbstractGrammar.prototype._optional = function optional(fn) {
if (!fn.call(this)) {
this._setIntermediate(undefined);
}
return true;
};
//
// ### function token ()
// Default token rule implementation
//
AbstractGrammar.prototype.token = function token() {
if (!this._word()) return false;
var token = this._getIntermediate();
// Match whitespace after token and close 'chars'
if (this._rule('spaces')) {
this._setIntermediate([token, token], true);
return true;
} else {
this._setIntermediate(undefined);
return false;
}
};
//
// ### function anything ()
// Default `anything` rule implementation
//
AbstractGrammar.prototype.anything = function anything() {
return this._skip();
};
//
// ### function space ()
// Default `space` rule implementation
//
AbstractGrammar.prototype.space = function space() {
return this._fnMatch(function(v) { return /^[\s\n\r]$/.test(v) });
};
//
// ### function spaces ()
// Default `spaces` rule implementation
//
AbstractGrammar.prototype.spaces = function spaces() {
return this._any(function() {
return this._rule('space');
});
};
//
// ### function fromTo ()
// Default `fromTo` rule implementation
//
AbstractGrammar.prototype.fromTo = function fromTo() {
this._skip();
var from = this._getIntermediate();
this._skip();
var to = this._getIntermediate();
return this._fromTo(from, to);
};
//
// ### function char ()
// Default `char` rule implementation
//
AbstractGrammar.prototype.char = function char() {
return this._fnMatch(function(curr) {
return typeof curr === 'string' &&
curr.length === 1;
});
};
//
// ### function letter ()
// Default `letter` rule implementation
//
AbstractGrammar.prototype.letter = function letter() {
return this._fnMatch(function(curr) {
return /^[a-zA-Z]$/.test(curr);
});
};
//
// ### function letter ()
// Default `digit` rule implementation
//
AbstractGrammar.prototype.digit = function digit() {
return this._fnMatch(function(curr) {
return /^\d$/.test(curr);
});
};
//
// ### function seq ()
// Default `seq` rule implementation
//
AbstractGrammar.prototype.seq = function seq() {
this._skip();
var seq = this._getIntermediate();
return this._seq(seq);
};
//
// ### function listOf ()
// Default `listOf` rule implementation
//
AbstractGrammar.prototype.listOf = function listOf() {
this._skip();
var rule = this._getIntermediate();
this._skip();
var sep = this._getIntermediate();
if (!this._rule(rule)) {
this._setIntermediate([], true);
return true;
}
var list = [this._getIntermediate()];
while (this._seq(sep)) {
if (!this._rule(rule)) return false;
list.push(this._getIntermediate());
}
this._setIntermediate(list, true);
return true;
};
//
// ### function empty ()
// Default `empty` rule implementation
//
AbstractGrammar.prototype.empty = function empty() {
return true;
};
//
// ### function end ()
// Default `end` rule implementation
//
AbstractGrammar.prototype.end = function end() {
return this._isEnd();
};