-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.js
659 lines (554 loc) · 14.2 KB
/
backup.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
'use strict';
/**
* Module dependencies
*/
const assert = require('assert');
const Emitter = require('events');
const Lexer = require('snapdragon-lexer');
const Node = require('snapdragon-node');
/**
* Local dependencies
*/
const Scopes = require('./lib/scopes');
const Stack = require('./lib/stack');
const State = require('./lib/state');
/**
* Create a new `Parser` with the given `input` and `options`.
*
* ```js
* const Snapdragon = require('snapdragon');
* const Parser = Snapdragon.Parser;
* const parser = new Parser();
* ```
* @param {String} `input`
* @param {Object} `options`
* @api public
*/
class Parser extends Emitter {
constructor(input, options = {}) {
super();
if (typeof input !== 'string') {
options = input;
input = '';
}
if (Parser.isParser(options)) {
return this.create(options.options, options);
}
this.isParser = true;
this.options = Object.assign({ type: 'root' }, options);
this.Lexer = this.options.Lexer || Lexer;
this.lexer = this.options.lexer || new this.Lexer(this.options);
this.contexts = [];
this.Scopes = this.options.Scopes || Scopes;
this.Stack = this.options.Stack || Stack;
this.State = this.options.State || State;
this.Node = this.options.Node || Node;
this.Scopes = this.Scopes.bind(null, this, this.Stack);
this.State = this.State.bind(null, this, this.Stack);
this.node = this.node.bind(this);
this.handlers = new Map();
this.types = new Set();
sync('string', this, this.lexer);
sync('input', this, this.lexer);
this.init(input);
}
/**
* Initialize parser state properties
*/
init(input) {
this.lexer.init(input);
this.scopes = new this.Scopes();
this.state = new this.State();
this.bos = this.node({ type: 'bos', value: '' });
this.eos = this.node({ type: 'eos', value: '' });
this.ast = this.node({ type: this.options.type, nodes: [] });
this.scopes.push(this.node({type: 'root'}));
this.state.push(this.ast);
this.emit('init');
}
/**
* Push a `parser` onto the contexts stack, or pop and return a parser.
*/
context(parser) {
if (parser) {
this.contexts.push(parser);
} else {
return this.contexts.pop();
}
}
/**
* Create a new [Node](#node) with the given `value` and `type`.
*
* ```js
* const node = parser.node({type: 'slash', value: '/'});
* // sugar for
* const Node = require('snapdragon-node');
* const node = Node({type: 'slash', value: '/'});
* ```
* @name .node
* @param {Object} `node` The object to use to create a node
* @return {Object} returns the created [Node](#node) instance.
* @api public
*/
node(node, value) {
assert(node, 'expected a string or object');
if (typeof node === 'string') {
return this.node({type: node, value});
}
if (!this.isNode(node)) {
node = new this.Node(node);
}
const nodes = (nodes, parent) => {
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i] = this.node(nodes[i]);
node.parent = parent;
node.index = i;
}
return nodes;
};
if (Array.isArray(node.nodes)) {
nodes(node.nodes, node);
}
this.emit('node', node);
return node;
}
/**
* Returns true if the given value is an instance of [snapdragon-node][].
*
* @name .isNode
* @param {Object} `node`
* @return {Boolean}
* @api public
*/
isNode(node) {
return this.Node.isNode(node);
}
/**
* Register handler of the given `type`.
*
* ```js
* parser.set('all', function(tok) {
* // do stuff to tok
* return tok;
* });
* ```
* @name .set
* @param {String} `type`
* @param {Function} `handler`
* @api public
*/
set(type, handler) {
assert.equal(typeof type, 'string', 'expected a string');
// if it's a noop, just return the token
if (typeof handler !== 'function') {
handler = tok => tok;
}
if (handler.fn) return handler;
const wrapped = tok => {
let node = handler.call(this, tok);
if (isObject(node) && !this.isNode(node)) {
node = this.node(node);
}
if (!this.isNode(node)) return;
if (!node.type) {
node.type = type;
}
this.emit('handled', node);
this.emit(node.type, node);
return node;
};
wrapped.fn = handler;
if (handler.name) {
Reflect.defineProperty(wrapped, 'name', { value: handler.name });
}
this.handlers.set(type, wrapped);
if (!this.types.has(type)) {
this.types.add(type);
}
return this;
}
/**
* Get a registered handler function.
*
* ```js
* handlers.set('star', function() {
* // do parser, lexer, or compiler stuff
* });
* const star = handlers.get('star');
* ```
* @name .get
* @param {String} `type`
* @param {Function} `fn` The handler function to register.
* @api public
*/
get(type) {
const handler = this.handlers.get(type) || this.handlers.get('default');
assert.equal(typeof handler, 'function', `expected handler "${type}" to be a function`);
return handler;
}
has(type) {
return this.handlers.has(type);
}
/**
* Get the previous node from the state
*/
current() {
return this.state.current();
}
/**
* Get the previous node from the state
*/
prev() {
return this.state.current();
}
/**
* Get the last child node of the current node on the state
*/
last() {
let prev = this.prev() || this.ast;
while (prev && prev.nodes && prev.nodes.length) {
prev = prev.nodes[prev.nodes.length - 1];
}
return prev;
}
/**
* Proxy lexer methods
*/
peek() {
return this.lexer.peek();
}
/**
* Capture a node of the given `type`.
*
* @name .capture
* @param {String} `type` (required)
* @param {RegExp} `regex` (optional)
* @param {Function} `lexerFn` (optional)
* @param {Function} `parserFn` (optional)
* @return {Object} Returns the Parser instance for chaining.
* @api public
*/
capture(type, regex, lexerFn, parserFn) {
if (!isRegex(regex)) {
return this.set(type, regex);
}
if (typeof parserFn === 'undefined') {
parserFn = lexerFn;
lexerFn = null;
}
this.lexer.capture(type, regex, lexerFn);
return this.set(type, parserFn);
}
isInside(type) {
return this.state.isInside(type);
}
isClose(node, parent) {
if (typeof parent.isClose === 'function') {
return parent.isClose(node);
}
const segs = node.type.split('.');
if (segs[0] !== parent.type) {
return false;
}
return segs[1] === 'close';
}
isBlock(node) {
return Array.isArray(node.nodes) && node.nodes.length > 0;
}
isBlockOpen(node, prev = this.prev()) {
assert(this.isNode(node), 'expected a node');
if (isFunction(prev.isOpen) && prev.isOpen(node)) return true;
if (isFunction(node.isOpen) && !node.nodes && node.isOpen()) return true;
return node.type.length >= 5 && node.type.slice(-4) === 'open';
}
isBlockClose(node, prev = this.prev()) {
assert(this.isNode(node), 'expected a node');
if (isFunction(prev.isClose) && prev.isClose(node)) return true;
if (isFunction(node.isClose) && !node.nodes && node.isClose()) return true;
return node.type.length >= 6 && node.type.slice(-5) === 'close';
}
isClosedBlock(node) {
return this.isBlock(node) && this.isBlockClose(node.last, node);
}
isOpenBlock(node) {
return this.isBlock(node) && !this.isBlockClose(node.last, node);
}
/**
* Push a node onto the `nodes` array of the "current" node
* on the `state.stack`.
*
* ```js
* parser.set('default', function(tok) {
* return this.push(this.node(tok));
* });
* ```
* @name .push
* @emits push
* @param {Object} `node` (required)
* @return {Object} `node`
* @api public
*/
push(node) {
if (!node) return;
if (isObject(node) && node.type && !this.isNode(node)) {
node = this.node(node);
}
// set the current "scope" on the node
define(node, 'scope', this.scope);
this.scope.push(node);
this.emit('push', node);
const prev = this.prev();
// allow users to do this with custom code in handlers
if (node.skip !== true) {
if (this.isBlock(node) && this.isBlockOpen(node.nodes[0])) {
this.state.push(node);
}
if (this.isBlock(prev) && this.isClose(node, prev)) {
this.pop(node);
}
}
prev.push(node);
if (node.type === 'brace') {
console.log(this.state.stack)
}
return node;
}
pop(node) {
const block = this.state.pop();
assert(block && Array.isArray(block.nodes), 'expected a block node');
if (node && !this.isClose(node, block)) {
this.error(`expected "${block.type}.close" node, received: "${node.type}"`);
}
return block;
}
/**
* Gets the next token from the lexer, then calls the registered
* parser handler for `token.type` on the token.
*
* @name .next
* @return {any} Returns whatever value the handler returns.
* @api public
*/
next() {
const tok = this.lexer.next();
if (!tok) return;
this.lexer.push(tok);
try {
const handler = this.get(tok.type);
return handler.call(this, tok);
} catch (err) {
err.name = 'ParserError';
this.error(err);
}
}
/**
* Expect the given type, or throw an exception.
*
* @param {String} type
* @api private
*/
expect(type) {
const next = this.peek();
if (next.type !== type) {
throw new Error(`expected "${type}", but got "${next.type}"`);
}
return this.next();
}
/**
* Accept the given `type`.
*
* @param {String} type
* @api private
*/
accept(type) {
const next = this.peek();
if (next.type === type) {
return this.next();
}
}
/**
* Parses the given `input` string and returns an AST object.
*
* ```js
* const ast = parser.parse('foo/bar');
* ```
* @name .parse
* @param {String} `input`
* @return {Object} Returns an AST (abstract syntax tree).
* @api public
*/
parse(input, options) {
assert.equal(typeof input, 'string', 'expected input to be a string');
this.init(input);
const bos = this.handlers.get('bos');
const eos = this.handlers.get('eos');
this.push(bos ? bos.call(this, this.bos) : this.bos);
while (!this.lexer.eos()) this.push(this.next());
this.push(eos ? eos.call(this, this.eos) : this.eos);
this.emit('parsed', this.ast);
this.fail();
return this.ast;
}
/**
* Creates a new Parser instance with the given options, and copy
* the handlers from the current instance to the new instance.
*
* @param {Object} `options`
* @param {Object} `parent` Optionally pass a different parser instance to copy handlers from.
* @return {Object} Returns a new Parser instance
* @api public
*/
create(options) {
const parser = new this.constructor(options);
parser.lexer.handlers = this.lexer.handlers;
parser.lexer.types = this.lexer.types;
parser.handlers = this.handlers;
parser.types = this.types;
parser.input = '';
return parser;
}
/**
* Concat nodes from another AST to `node.nodes`.
*
* @param {Object} `node`
* @param {Object} `ast`
* @return {Object}
* @api public
*/
concat(node, ast) {
for (let child of ast.nodes) {
if (child.type !== 'bos' && child.type !== 'eos') {
node.push(child);
}
}
return node;
}
/**
* Returns true if listeners are registered for even `name`.
*
* @name .hasListeners
* @param {string} `name`
* @return {boolean}
* @api public
*/
hasListeners(name) {
return this.listenerCount(name) > 0;
}
/**
* Throw a formatted error message with details including the cursor position.
*
* ```js
* parser.set('foo', function(tok) {
* if (tok.value !== 'foo') {
* throw this.error('expected token.value to be "foo"', tok);
* }
* });
* ```
* @name .error
* @param {String} `msg` Message to use in the Error.
* @param {Object} `node`
* @return {undefined}
* @api public
*/
error(err) {
if (typeof err === 'string') {
err = new Error(err);
}
if (this.hasListeners('error')) {
this.emit('error', err);
} else {
throw err;
}
}
/**
* Fail when a closing delimiter is missing.
*/
fail() {
const node = this.state.pop();
if (node.type !== 'root') {
this.error(new SyntaxError(`unclosed: "${node.type}"`));
}
}
/**
* Get the previous node from the state
*/
get scope() {
return this.scopes.current();
}
/**
* Get the part of the input string has has already been parsed.
* @return {String}
* @api public
*/
get parsed() {
return this.lexer.consumed;
}
/**
* Returns true if the given value is an instance of snapdragon `Parser`.
*
* ```js
* const Parser = require('snapdragon/lib/parser');
* const parser = new Parser();
* console.log(Parser.isParser(parser)); //=> true
* console.log(Parser.isParser({})); //=> false
* ```
* @param {Object} `parser`
* @returns {Boolean}
* @api public
*/
static isParser(parser) {
return isObject(parser) && parser.isParser === true;
}
}
function define(obj, key, value) {
Reflect.defineProperty(obj, key, {
enumerable: false,
configurable: true,
writable: true,
value: value
});
}
function getter(key, parser) {
Reflect.defineProperty(parser, key, {
get: () => parser.lexer[key]
});
}
function sync(key, parser) {
Reflect.defineProperty(parser, key, {
set: function(value) {
parser.lexer[key] = value;
},
get: function() {
return parser.lexer[key];
}
});
}
/**
* Returns true if value is a function
* @param {any} value
* @return {Boolean}
*/
function isFunction(value) {
return typeof value === 'function';
}
/**
* Returns true if value is an object
* @param {any} value
* @return {Boolean}
*/
function isObject(val) {
return val && typeof val === 'object' && !Array.isArray(val);
}
/**
* Returns true if value is a RegExp
* @param {any} value
* @return {Boolean}
*/
function isRegex(val) {
return val instanceof RegExp;
}
/**
* Expose `Parser`
* @type {Function}
*/
module.exports = Parser;