-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmyna.js
1368 lines (1368 loc) · 60.9 KB
/
myna.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Myna Parsing Library
// Copyright (c) 2016 Christopher Diggins
// Usage permitted under terms of MIT License
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
// A parsing combinator library for JavaScript/TypeScript based on the PEG formalism.
// For more information see http://www.github.com/cdiggins/myna-parser
var Myna;
(function (Myna) {
// A parser error class
var ParserError = (function (_super) {
__extends(ParserError, _super);
function ParserError(message) {
_super.call(this, message);
this.type = 'ParserError';
}
return ParserError;
}(Error));
Myna.ParserError = ParserError;
//====================================================================================
// Internal variables used by the Myna library
// A lookup table of all grammars registered with the Myna module
Myna.grammars = {};
// A lookup table of all named rules registered with the Myna module
Myna.allRules = {};
// A lookup table of parsing functions for each registered grammar
Myna.parsers = {};
//===========================================================================
// class ParseLocation
// Used to indicate the location of the parser to the user in a pleasant way.
var ParseLocation = (function () {
function ParseLocation(input, index) {
this.input = input;
this.index = index;
this.lineNum = 0;
this.colNum = 0;
this.lineStart = 0;
this.lineEnd = 0;
var r1 = 0;
var r2 = 1;
for (var i = 0; i < this.index; ++i) {
if (this.input.charCodeAt(i) == 13) {
this.lineStart = i;
r1++;
}
if (this.input.charCodeAt(i) == 10) {
this.lineStart = i;
r2++;
}
}
for (this.lineEnd = this.index; this.lineEnd < this.input.length; ++this.lineEnd) {
if (this.input.charCodeAt(this.lineEnd) == 13 || this.input.charCodeAt(this.lineEnd) == 10)
break;
}
this.lineNum = r1 > r2 ? r1 : r2;
this.colNum = this.index - this.lineStart;
this.lineText = this.input.substring(this.lineStart, this.lineEnd);
this.pointerText = Array(this.colNum).join(' ') + "^";
}
ParseLocation.prototype.toString = function () {
return "Index " + this.index
+ ", Line " + this.lineNum
+ ", Column " + this.colNum
+ "\n" + this.lineText
+ "\n" + this.pointerText;
};
return ParseLocation;
}());
Myna.ParseLocation = ParseLocation;
//===========================================================================
// class ParseState
// This stores the state of the parser and is passed to the parse and match functions.
var ParseState = (function () {
function ParseState(input, index, nodes) {
this.input = input;
this.index = index;
this.nodes = nodes;
this.length = 0;
this.rules = [];
this.length = this.input.length;
}
Object.defineProperty(ParseState.prototype, "location", {
// Returns an object that representation of the location.
get: function () {
return new ParseLocation(this.input, this.index);
},
enumerable: true,
configurable: true
});
return ParseState;
}());
Myna.ParseState = ParseState;
// Represents a node in the generated parse tree. These nodes are returned by the Rule.parse function. If a Rule
// has the "_createAstNode" field set to true (because you created the rule using the ".ast" property), then the
// generated node will also be added to the constructed parse tree.
var AstNode = (function () {
// Constructs a new node associated with the given rule.
function AstNode(rule, input, start, end) {
if (start === void 0) { start = 0; }
if (end === void 0) { end = -1; }
this.rule = rule;
this.input = input;
this.start = start;
this.end = end;
// The list of child nodes in the parse tree.
// This is not allocated unless used, to minimize memory consumption
this.children = null;
}
Object.defineProperty(AstNode.prototype, "name", {
// Returns the name of the rule associated with this node
get: function () { return this.rule != null ? this.rule.name : "unnamed"; },
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "fullName", {
// Returns the name of the rule, preceded by the grammar name, associated with this node
get: function () { return this.rule != null ? this.rule.fullName : "unnamed"; },
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "allText", {
// Returns the parsed text associated with this node's start and end locations
get: function () { return this.input.slice(this.start, this.end); },
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "isLeaf", {
// Returns true if this node has no children
get: function () { return this.children == null || this.children.length == 0; },
enumerable: true,
configurable: true
});
// Returns the first child with the given name, or null if no named child is found.
AstNode.prototype.child = function (name) {
if (this.children)
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var c = _a[_i];
if (c.name == name)
return c;
}
return null;
};
Object.defineProperty(AstNode.prototype, "_firstChildStart", {
// The position of the first child, or the end position for the entire node if no children
get: function () {
return this.isLeaf ? this.end : this.children[0].start;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "_lastChildEnd", {
// The end position of the last child, or the end position for the entire node if no children
get: function () {
return this.isLeaf ? this.end : this.children[0].end;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "beforeChildrenText", {
// Returns the text before the children, or if no children returns the entire text.
get: function () {
return this.input.slice(this.start, this._firstChildStart);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "afterChildrenText", {
// Returns the text after the children, or if no children returns the empty string.
get: function () {
return this.input.slice(this._lastChildEnd, this.end);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AstNode.prototype, "allChildrenText", {
// Returns the text from the beginning of the first child to the end of the last child.
get: function () {
return this.input.slice(this._firstChildStart, this._lastChildEnd);
},
enumerable: true,
configurable: true
});
// Returns the AST as a string for debug and test purposes
AstNode.prototype.toString = function () {
var contents = this.isLeaf
? this.allText
: this.children.map(function (c) { return c.toString(); }).join(" ");
return "(" + this.rule.name + ': ' + contents + ")";
};
return AstNode;
}());
Myna.AstNode = AstNode;
//===============================================================
// class Rule
// A Rule is both a rule in the PEG grammar and a parser. The parse function takes
// a particular parse location (in either a string, or array of tokens) and will return
// the location of the end of the parse if successful or null if not successful.
var Rule = (function () {
// Constructor
// Note: child-rules are exposed as a public field
function Rule(rules) {
this.rules = rules;
// Identifies individual rule
this.name = "";
// Identifies the grammar that this rule belongs to
this.grammarName = "";
// Identifies types of rules. Rules can have "types" that are different than the class name
this.type = "";
// Used to provide access to the name of the class
this.className = "Rule";
// Indicates whether generated nodes should be added to the abstract syntax tree
this._createAstNode = false;
// A parser function, computed in a rule's constructor. If successful returns either the original or a new
// ParseState object. If it fails it returns null.
this.parser = null;
// A lexer function, computed in a rule's constructor. The lexer may update the ParseState if successful.
// If it fails it is required that the lexer restore the ParseState index to the previous state.
// Lexers should only update the index.
this.lexer = null;
}
// Creates a node with the given children. This is used to manually build parts of the AST.
Rule.prototype.node = function (text) {
if (text === void 0) { text = ''; }
var children = [];
for (var _i = 1; _i < arguments.length; _i++) {
children[_i - 1] = arguments[_i];
}
var r = new AstNode(this, text, 0, text.length);
r.children = children;
return r;
};
// Parses a string into an AST node
Rule.prototype.parse = function (s) {
return Myna.parse(this, s);
};
// Sets the name of the rule, and the grammar
// Warning: this modifies the rule, use "copy" first if you don't want to update the rule.
Rule.prototype.setName = function (grammarName, ruleName) {
this.grammarName = grammarName;
this.name = ruleName;
return this;
};
Object.defineProperty(Rule.prototype, "definition", {
// Returns a default definition of the rule
get: function () {
return this.className + "(" + this.rules.map(function (r) { return r.toString(); }).join(", ") + ")";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "fullName", {
// Returns the name of the rule preceded by the grammar name and a "."
get: function () {
return this.grammarName + "." + this.name;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "nameOrDefinition", {
// Returns either the name of the rule, or it's definition
get: function () {
return this.name
? this.fullName
: this.definition;
},
enumerable: true,
configurable: true
});
// Returns a string representation of the rule
Rule.prototype.toString = function () {
return this.nameOrDefinition;
};
Object.defineProperty(Rule.prototype, "firstChild", {
// Returns the first child rule
get: function () {
return this.rules[0];
},
enumerable: true,
configurable: true
});
// Sets the "type" associated with the rule.
// This is useful for tracking how a rule was created.
Rule.prototype.setType = function (type) {
this.type = type;
return this;
};
// Returns a copy of this rule with default values for all fields.
// Note: Every new rule class must override cloneImplemenation
Rule.prototype.cloneImplementation = function () {
throw new Error("Missing override for cloneImplementation");
};
Object.defineProperty(Rule.prototype, "copy", {
// Returns a copy of this rule with all fields copied.
get: function () {
var r = this.cloneImplementation();
if (typeof (r) !== typeof (this))
throw new Error("Error in implementation of cloneImplementation: not returning object of correct type");
r.name = this.name;
r.grammarName = this.grammarName;
r._createAstNode = this._createAstNode;
return r;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "hasAstChildRule", {
// Returns true if any of the child rules are "ast rules" meaning they create nodes in the parse tree.
get: function () {
return this.rules.filter(function (r) { return r.createsAstNode; }).length > 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "createsAstNode", {
// Returns true if this rule when parsed successfully will create a node in the parse tree.
// Some rules will override this function.
get: function () {
return this._createAstNode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "nonAdvancing", {
// Returns true if this rule doesn't advance the input
get: function () {
return false;
},
enumerable: true,
configurable: true
});
// Returns a string that describes the AST nodes created by this rule.
// Will throw an exception if this is not a valid AST rule (this.isAstRule != true)
Rule.prototype.astRuleDefn = function (inSeq, inChoice) {
if (inSeq === void 0) { inSeq = false; }
if (inChoice === void 0) { inChoice = false; }
var rules = this.rules.filter(function (r) { return r.createsAstNode; });
if (!rules.length)
return this.name;
if (rules.length == 1) {
var result = rules[0].astRuleNameOrDefn(inSeq, inChoice);
if (this instanceof Quantified)
result += "[" + this.min + "," + this.max + "]";
return result;
}
if (this instanceof Sequence) {
var tmp = rules.map(function (r) { return r.astRuleNameOrDefn(true, false); }).join(",");
if (inSeq)
return tmp;
return "seq(" + tmp + ")";
}
if (this instanceof Choice) {
var tmp = rules.map(function (r) { return r.astRuleNameOrDefn(false, true); }).join(",");
if (inChoice)
return tmp;
return "choice(" + tmp + ")";
}
throw new Error("Internal error: not a valid AST rule");
};
// Returns a string that is either the name of the AST parse node, or a definition
// (schema) describing the makeup of the rules.
Rule.prototype.astRuleNameOrDefn = function (inSeq, inChoice) {
if (inSeq === void 0) { inSeq = false; }
if (inChoice === void 0) { inChoice = false; }
if (this._createAstNode)
return this.name;
return this.astRuleDefn(inSeq, inChoice);
};
Object.defineProperty(Rule.prototype, "opt", {
//======================================================
// Extensions to support method/property chaining.
// This is also known as a fluent API syntax
get: function () { return opt(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "zeroOrMore", {
get: function () { return zeroOrMore(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "oneOrMore", {
get: function () { return oneOrMore(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "at", {
get: function () { return at(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "not", {
get: function () { return not(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "advance", {
get: function () { return this.then(Myna.advance); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "ws", {
get: function () { return this.then(Myna.ws); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "all", {
get: function () { return this.then(Myna.all); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "end", {
get: function () { return this.then(Myna.end); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "assert", {
get: function () { return assert(this); },
enumerable: true,
configurable: true
});
Object.defineProperty(Rule.prototype, "ast", {
get: function () { return new AstRule(this); },
enumerable: true,
configurable: true
});
Rule.prototype.then = function (r) { return seq(this, r); };
Rule.prototype.thenAt = function (r) { return this.then(at(r)); };
Rule.prototype.thenNot = function (r) { return this.then(not(r)); };
Rule.prototype.or = function (r) { return choice(this, r); };
Rule.prototype.until = function (r) { return repeatWhileNot(this, r); };
Rule.prototype.untilPast = function (r) { return repeatUntilPast(this, r); };
Rule.prototype.repeat = function (count) { return repeat(this, count); };
Rule.prototype.quantified = function (min, max) { return quantified(this, min, max); };
Rule.prototype.delimited = function (delimiter) { return delimited(this, delimiter); };
Rule.prototype.unless = function (r) { return unless(this, r); };
return Rule;
}());
Myna.Rule = Rule;
//===============================================================
// Rule derived classes
// These are the core Rule classes of Myna. Normally you would not use theses directly but use the factory methods
// If you fork this code, think twice before adding new classes here. Maybe you can implement your new Rule
// in terms of functions or other low-level rules. Then you can be happy knowing that the same code is being
// re-used and tested all the time.
// Creates a node in the AST tree
var AstRule = (function (_super) {
__extends(AstRule, _super);
function AstRule(r) {
var _this = this;
_super.call(this, [r]);
this.r = r;
this.type = 'ast';
this.className = "AstRule";
this._createAstNode = true;
this.parser = function (p) {
var originalIndex = p.index;
var originalNodes = p.nodes;
p.nodes = [];
p.rules.push(_this);
if (!r.parser(p)) {
p.rules.pop();
p.nodes = originalNodes;
p.index = originalIndex;
return false;
}
else {
p.rules.pop();
var node = new AstNode(_this, p.input, originalIndex, p.index);
node.children = p.nodes;
p.nodes = originalNodes;
p.nodes.push(node);
return true;
}
};
this.lexer = r.lexer;
}
return AstRule;
}(Rule));
Myna.AstRule = AstRule;
// Matches a series of rules in order. Succeeds only if all sub-rules succeed.
var Sequence = (function (_super) {
__extends(Sequence, _super);
function Sequence(rule1, rule2) {
_super.call(this, [rule1, rule2]);
this.rule1 = rule1;
this.rule2 = rule2;
this.type = "seq";
this.className = "Sequence";
this.parser = function (p) {
var originalCount = p.nodes.length;
var originalIndex = p.index;
if (rule1.parser(p) === false)
// The first parser will restore everything automatically
return false;
if (rule2.parser(p) === false) {
// Any created nodes need to be popped off the list
if (p.nodes.length !== originalCount)
p.nodes.splice(-1, p.nodes.length - originalCount);
// Assure that the parser is restored to its original position
p.index = originalIndex;
return false;
}
return true;
};
this.lexer = function (p) {
var original = p.index;
if (rule1.lexer(p) === false)
return false;
if (rule2.lexer(p) === false) {
p.index = original;
return false;
}
return true;
};
// When none of the child rules create a node, we can use the lexer to parse
if (!this.createsAstNode)
this.parser = this.lexer;
}
Object.defineProperty(Sequence.prototype, "definition", {
get: function () {
var result = this.rules.map(function (r) { return r.toString(); }).join(" ");
if (this.rules.length > 1)
result = "(" + result + ")";
return result;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sequence.prototype, "nonAdvancing", {
get: function () {
return this.rules.every(function (r) { return r.nonAdvancing; });
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sequence.prototype, "createsAstNode", {
get: function () {
return this._createAstNode || this.hasAstChildRule;
},
enumerable: true,
configurable: true
});
Sequence.prototype.cloneImplementation = function () { return new Sequence(this.rule1, this.rule2); };
return Sequence;
}(Rule));
Myna.Sequence = Sequence;
// Tries to match each rule in order until one succeeds. Succeeds if any of the sub-rules succeed.
var Choice = (function (_super) {
__extends(Choice, _super);
function Choice(rule1, rule2) {
_super.call(this, [rule1, rule2]);
this.rule1 = rule1;
this.rule2 = rule2;
this.type = "choice";
this.className = "Choice";
this.parser = function (p) {
return rule1.parser(p) || rule2.parser(p);
};
this.lexer = function (p) {
return rule1.lexer(p) || rule2.lexer(p);
};
// When none of the child rules create a node, we can use the lexer to parse
if (!this.createsAstNode)
this.parser = this.lexer;
}
Object.defineProperty(Choice.prototype, "definition", {
get: function () {
var result = this.rules.map(function (r) { return r.toString(); }).join(" / ");
if (this.rules.length > 1)
result = "(" + result + ")";
return result;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Choice.prototype, "nonAdvancing", {
get: function () {
return this.rules.every(function (r) { return r.nonAdvancing; });
},
enumerable: true,
configurable: true
});
Object.defineProperty(Choice.prototype, "createsAstNode", {
get: function () {
return this._createAstNode || this.hasAstChildRule;
},
enumerable: true,
configurable: true
});
Choice.prototype.cloneImplementation = function () { return new Choice(this.rule1, this.rule2); };
return Choice;
}(Rule));
Myna.Choice = Choice;
// A generalization of several rules such as zeroOrMore (0+), oneOrMore (1+), opt(0 or 1),
// When matching with an unbounded upper limit set the maxium to -1
var Quantified = (function (_super) {
__extends(Quantified, _super);
function Quantified(rule, min, max) {
var _this = this;
if (min === void 0) { min = 0; }
if (max === void 0) { max = Infinity; }
_super.call(this, [rule]);
this.min = min;
this.max = max;
this.type = "quantified";
this.className = "Quantified";
if (max === Infinity && rule.nonAdvancing)
throw new Error("Rule would create an infinite loop");
this.parser = function (p) {
var originalCount = p.nodes.length;
var originalIndex = p.index;
for (var i = 0; i < max; ++i) {
// If parsing the rule fails, we return the last result, or failed
// if the minimum number of matches is not met.
if (rule.parser(p) === false) {
if (i >= min)
return true;
// Any created nodes need to be popped off the list
if (p.nodes.length !== originalCount)
p.nodes.splice(-1, p.nodes.length - originalCount);
// Assure that the parser is restored to its original position
p.index = originalIndex;
return false;
}
// Check for progress, to assure we aren't hitting an infinite loop
debugAssert(max !== Infinity || p.index !== originalIndex, _this);
}
return true;
};
this.lexer = function (p) {
var originalIndex = p.index;
for (var i = 0; i < max; ++i) {
if (rule.lexer(p) === false) {
if (i >= min)
return true;
p.index = originalIndex;
return false;
}
// Check for progress, to assure we aren't hitting an infinite loop
debugAssert(max !== Infinity || p.index !== originalIndex, _this, "Infinite loop");
}
return true;
};
// When none of the child rules create a node, we can use the lexer to parse
if (!this.createsAstNode)
this.parser = this.lexer;
}
Object.defineProperty(Quantified.prototype, "definition", {
// Used for creating a human readable definition of the grammar.
get: function () {
if (this.min == 0 && this.max == 1)
return this.firstChild.toString() + "?";
if (this.min == 0 && this.max == Infinity)
return this.firstChild.toString() + "*";
if (this.min == 1 && this.max == Infinity)
return this.firstChild.toString() + "+";
return this.firstChild.toString() + "{" + this.min + "," + this.max + "}";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Quantified.prototype, "createsAstNode", {
get: function () {
return this._createAstNode || this.hasAstChildRule;
},
enumerable: true,
configurable: true
});
Quantified.prototype.cloneImplementation = function () { return new Quantified(this.firstChild, this.min, this.max); };
return Quantified;
}(Rule));
Myna.Quantified = Quantified;
// Matches a child rule zero or once.
var Optional = (function (_super) {
__extends(Optional, _super);
function Optional(rule) {
_super.call(this, rule, 0, 1);
this.type = "optional";
this.className = "Optional";
this.parser = function (p) {
rule.parser(p);
return true;
};
this.lexer = function (p) {
rule.lexer(p);
return true;
};
// When none of the child rules create a node, we can use the lexer to parse
if (!this.createsAstNode)
this.parser = this.lexer;
}
Object.defineProperty(Optional.prototype, "definition", {
// Used for creating a human readable definition of the grammar.
get: function () {
return this.firstChild.toString() + "?";
},
enumerable: true,
configurable: true
});
Optional.prototype.cloneImplementation = function () { return new Optional(this.firstChild); };
return Optional;
}(Quantified));
Myna.Optional = Optional;
// Advances the parser by one token unless at the end
var Advance = (function (_super) {
__extends(Advance, _super);
function Advance() {
_super.call(this, []);
this.type = "advance";
this.className = "Advance";
this.lexer = function (p) {
return p.index < p.length ? ++p.index >= 0 : false;
};
this.parser = this.lexer;
}
Object.defineProperty(Advance.prototype, "definition", {
get: function () { return "<advance>"; },
enumerable: true,
configurable: true
});
Advance.prototype.cloneImplementation = function () { return new Advance(); };
return Advance;
}(Rule));
Myna.Advance = Advance;
// Advances the parser by one token if the predicate is true.
var AdvanceIf = (function (_super) {
__extends(AdvanceIf, _super);
function AdvanceIf(condition) {
_super.call(this, [condition]);
this.type = "advanceIf";
this.className = "AdvanceIf";
this.lexer = function (p) {
return condition.lexer(p) && p.index < p.length ? ++p.index !== 0 : false;
};
this.parser = this.lexer;
}
Object.defineProperty(AdvanceIf.prototype, "definition", {
get: function () { return "advanceIf(" + this.firstChild.toString() + ")"; },
enumerable: true,
configurable: true
});
AdvanceIf.prototype.cloneImplementation = function () { return new AdvanceIf(this.firstChild); };
return AdvanceIf;
}(Rule));
Myna.AdvanceIf = AdvanceIf;
// Used to match a string in the input string, advances the token.
var Text = (function (_super) {
__extends(Text, _super);
function Text(text) {
_super.call(this, []);
this.text = text;
this.type = "text";
this.className = "Text";
var length = text.length;
var vals = [];
for (var i = 0; i < length; ++i)
vals.push(text.charCodeAt(i));
this.lexer = function (p) {
var index = p.index;
if (index + vals.length > p.input.length)
return false;
// TODO: consider pulling the sub-string out of the text.
for (var _i = 0, vals_1 = vals; _i < vals_1.length; _i++) {
var val = vals_1[_i];
if (p.input.charCodeAt(index++) !== val)
return false;
}
p.index = index;
return true;
};
this.parser = this.lexer;
}
Object.defineProperty(Text.prototype, "definition", {
get: function () { return '"' + escapeChars(this.text) + '"'; },
enumerable: true,
configurable: true
});
Text.prototype.cloneImplementation = function () { return new Text(this.text); };
return Text;
}(Rule));
Myna.Text = Text;
// Used to match a string in the input string ignoring case, advances the token.
var AnyCaseText = (function (_super) {
__extends(AnyCaseText, _super);
function AnyCaseText(text) {
_super.call(this, []);
this.text = text;
this.type = "anyCaseText";
this.className = "AnyCaseText";
text = text.toLowerCase();
this.text = text;
var length = text.length;
var vals = [];
for (var i = 0; i < length; ++i)
vals.push(text[i]);
this.lexer = function (p) {
var index = p.index;
if (index + vals.length > p.input.length)
return false;
for (var _i = 0, vals_2 = vals; _i < vals_2.length; _i++) {
var val = vals_2[_i];
if (p.input[index++].toLowerCase() !== val)
return false;
}
p.index = index;
return true;
};
this.parser = this.lexer;
}
Object.defineProperty(AnyCaseText.prototype, "definition", {
get: function () { return 'AnyCase("' + escapeChars(this.text) + '")'; },
enumerable: true,
configurable: true
});
AnyCaseText.prototype.cloneImplementation = function () { return new AnyCaseText(this.text); };
return AnyCaseText;
}(Rule));
Myna.AnyCaseText = AnyCaseText;
// Creates a rule that is defined from a function that generates the rule.
// This allows two rules to have a cyclic relation.
var Delay = (function (_super) {
__extends(Delay, _super);
function Delay(fn) {
_super.call(this, []);
this.fn = fn;
this.type = "delay";
this.className = "Delay";
var tmpParser = null;
this.parser = function (p) { return (tmpParser ? tmpParser : tmpParser = fn().parser)(p); };
var tmpLexer = null;
this.lexer = function (p) { return (tmpLexer ? tmpLexer : tmpLexer = fn().lexer)(p); };
}
Delay.prototype.cloneImplementation = function () { return new Delay(this.fn); };
Object.defineProperty(Delay.prototype, "definition", {
get: function () { return "<delay>"; },
enumerable: true,
configurable: true
});
Object.defineProperty(Delay.prototype, "createsAstNode", {
// It is assumed that a delay function creates an AST node,
get: function () {
return true;
},
enumerable: true,
configurable: true
});
return Delay;
}(Rule));
Myna.Delay = Delay;
//====================================================================================================================
// Predicates don't advance the input
// Used to identify rules that do not advance the input
var NonAdvancingRule = (function (_super) {
__extends(NonAdvancingRule, _super);
function NonAdvancingRule(rules) {
_super.call(this, rules);
this.type = "charSet";
}
Object.defineProperty(NonAdvancingRule.prototype, "nonAdvancing", {
get: function () {
return true;
},
enumerable: true,
configurable: true
});
return NonAdvancingRule;
}(Rule));
Myna.NonAdvancingRule = NonAdvancingRule;
// Returns true if the current token is in the token set.
var CharSet = (function (_super) {
__extends(CharSet, _super);
function CharSet(chars) {
_super.call(this, []);
this.chars = chars;
this.type = "charSet";
this.className = "CharSet";
var vals = [];
var length = chars.length;
for (var i = 0; i < length; ++i)
vals[i] = chars.charCodeAt(i);
this.lexer = function (p) {
// TODO: Try this instead, could be faster.
// chars.indexOf(p.input[p.index]) >= 0;
return vals.indexOf(p.input.charCodeAt(p.index)) >= 0;
};
this.parser = this.lexer;
}
Object.defineProperty(CharSet.prototype, "definition", {
get: function () { return "[" + escapeChars(this.chars) + "]"; },
enumerable: true,
configurable: true
});
;
CharSet.prototype.cloneImplementation = function () { return new CharSet(this.chars); };
return CharSet;
}(NonAdvancingRule));
Myna.CharSet = CharSet;
// Returns true if the current token is within a range of characters, otherwise returns false
var CharRange = (function (_super) {
__extends(CharRange, _super);
function CharRange(min, max) {
_super.call(this, []);
this.min = min;
this.max = max;
this.type = "charRange";
this.className = "CharRange";
var minCode = min.charCodeAt(0);
var maxCode = max.charCodeAt(0);
this.lexer = function (p) {
var code = p.input.charCodeAt(p.index);
return code >= minCode && code <= maxCode;
};
this.parser = this.lexer;
}
Object.defineProperty(CharRange.prototype, "definition", {
get: function () { return "[" + this.min + ".." + this.max + "]"; },
enumerable: true,
configurable: true
});
;
CharRange.prototype.cloneImplementation = function () { return new CharRange(this.min, this.max); };
return CharRange;
}(NonAdvancingRule));
Myna.CharRange = CharRange;
// Returns true only if the child rule fails to match.
var Not = (function (_super) {
__extends(Not, _super);
function Not(rule) {
_super.call(this, [rule]);
this.type = "not";
this.className = "Not";
var childLexer = rule.lexer;
this.lexer = function (p) {
if (p.index >= p.length)
return true;
var index = p.index;
if (childLexer(p) === false)
return true;
p.index = index;
return false;
};
this.parser = this.lexer;
}
Not.prototype.cloneImplementation = function () { return new Not(this.firstChild); };
Object.defineProperty(Not.prototype, "definition", {
get: function () { return "!" + this.firstChild.toString(); },
enumerable: true,
configurable: true
});
return Not;
}(NonAdvancingRule));
Myna.Not = Not;
// Returns true only if the child rule matches, but does not advance the parser
var At = (function (_super) {
__extends(At, _super);
function At(rule) {
_super.call(this, [rule]);
this.type = "at";
this.className = "At";
var childLexer = rule.lexer;
this.lexer = function (p) {
var index = p.index;
if (childLexer(p) === false)
return false;
p.index = index;
return true;
};
this.parser = this.lexer;
}
At.prototype.cloneImplementation = function () { return new At(this.firstChild); };
Object.defineProperty(At.prototype, "definition", {
get: function () { return "&" + this.firstChild.toString(); },
enumerable: true,
configurable: true
});
return At;
}(NonAdvancingRule));
Myna.At = At;
// Uses a function to return true or not based on the behavior of the predicate rule
var Predicate = (function (_super) {
__extends(Predicate, _super);
function Predicate(fn) {
_super.call(this, []);
this.fn = fn;
this.type = "predicate";
this.className = "Predicate";
this.lexer = fn;
this.parser = this.lexer;
}
Predicate.prototype.cloneImplementation = function () { return new Predicate(this.fn); };
Object.defineProperty(Predicate.prototype, "definition", {
get: function () { return "<predicate>"; },
enumerable: true,
configurable: true
});
return Predicate;