/
parser_public.ts
1844 lines (1641 loc) · 72.2 KB
/
parser_public.ts
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
import * as cache from "./cache"
import {exceptions} from "./exceptions_public"
import {
classNameFromInstance,
HashTable,
functionName
} from "../lang/lang_extensions"
import {resolveGrammar} from "./grammar/resolver"
import {
validateGrammar,
validateRuleName,
validateRuleDoesNotAlreadyExist,
validateRuleIsOverridden
} from "./grammar/checks"
import {
isEmpty,
map,
isArray,
reduce,
isObject,
cloneObj,
cloneArr,
first,
find,
contains,
flatten,
last,
dropRight,
isFunction,
has
} from "../utils/utils"
import {computeAllProdsFollows} from "./grammar/follow"
import {Token, tokenName, EOF, tokenLabel, hasTokenLabel} from "../scan/tokens_public"
import {gast} from "./grammar/gast_public"
import {
buildLookaheadForTopLevel,
buildLookaheadForOption,
buildLookaheadForOr,
buildLookaheadForMany,
buildLookaheadForManySep,
buildLookaheadForAtLeastOne,
buildLookaheadForAtLeastOneSep
} from "./grammar/lookahead"
import {TokenConstructor} from "../scan/lexer_public"
import {buildTopProduction} from "./gast_builder"
import {
NextAfterTokenWalker,
AbstractNextTerminalAfterProductionWalker,
NextTerminalAfterAtLeastOneWalker,
NextTerminalAfterAtLeastOneSepWalker,
NextTerminalAfterManyWalker,
NextTerminalAfterManySepWalker,
NextInsideOrWalker,
NextInsideAtLeastOneWalker,
AbstractNextPossibleTokensWalker,
NextInsideAtLeastOneSepWalker
} from "./grammar/interpreter"
import {IN} from "./constants"
export enum ParserDefinitionErrorType {
INVALID_RULE_NAME,
DUPLICATE_RULE_NAME,
INVALID_RULE_OVERRIDE,
DUPLICATE_PRODUCTIONS,
UNRESOLVED_SUBRULE_REF,
LEFT_RECURSION,
NONE_LAST_EMPTY_ALT
}
export interface IParserConfig {
/**
* Is the error recovery / fault tolerance of the Chevrotain Parser enabled.
*/
recoveryEnabled?:boolean
}
const DEFAULT_PARSER_CONFIG:IParserConfig = Object.freeze({
recoveryEnabled: false
})
export interface IRuleConfig<T> {
/**
* The function which will be invoked to produce the returned value for a production that have not been
* successfully executed and the parser recovered from.
*/
recoveryValueFunc?:() => T
/**
* Enable/Disable re-sync error recovery for this specific production.
*/
resyncEnabled?:boolean
}
const DEFAULT_RULE_CONFIG:IRuleConfig<any> = Object.freeze({
recoveryValueFunc: () => undefined,
resyncEnabled: true
})
export interface IParserDefinitionError {
message:string
type:ParserDefinitionErrorType
ruleName:string
}
export interface IParserDuplicatesDefinitionError extends IParserDefinitionError {
dslName:string
occurrence:number
parameter?:string
}
export interface IParserEmptyAlternativeDefinitionError extends IParserDefinitionError {
occurrence:number
alternative:number
}
export interface IParserUnresolvedRefDefinitionError extends IParserDefinitionError {
unresolvedRefName:string
}
// parameters needed to compute the key in the FOLLOW_SET map.
export interface IFollowKey {
ruleName:string
idxInCallingRule:number
inRule:string
}
/**
* OR([
* { WHEN:LA1, THEN_DO:XXX },
* { WHEN:LA2, THEN_DO:YYY },
* { WHEN:LA3, THEN_DO:ZZZ },
* ])
*/
export interface IOrAlt<T> {
WHEN:() => boolean
// TODO: change THEN_DO property to ALT (may need to modify gast builder)
THEN_DO:() => T
}
/**
* OR([
* {ALT:XXX },
* {ALT:YYY },
* {ALT:ZZZ }
* ])
*/
export interface IOrAltImplicit<T> {
ALT:() => T
}
export interface IParserState {
errors:exceptions.IRecognitionException[]
inputIdx:number
RULE_STACK:string[]
}
export type LookAheadFunc = () => boolean
export type GrammarAction = () => void
/**
* convenience used to express an empty alternative in an OR (alternation).
* can be used to more clearly describe the intent in a case of empty alternation.
*
* for example:
*
* 1. without using EMPTY_ALT:
*
* this.OR([
* {ALT: () => {
* this.CONSUME1(OneTok)
* return "1"
* }},
* {ALT: () => {
* this.CONSUME1(TwoTok)
* return "2"
* }},
* {ALT: () => { // implicitly empty because there are no invoked grammar rules (OR/MANY/CONSUME...) inside this alternative.
* return "666"
* }},
* ])
*
*
* * 2. using EMPTY_ALT:
*
* this.OR([
* {ALT: () => {
* this.CONSUME1(OneTok)
* return "1"
* }},
* {ALT: () => {
* this.CONSUME1(TwoTok)
* return "2"
* }},
* {ALT: EMPTY_ALT("666")}, // explicitly empty, clearer intent
* ])
*
*/
export function EMPTY_ALT<T>(value:T = undefined):() => T {
return function () {
return value
}
}
let EOF_FOLLOW_KEY:any = {}
/**
* A Recognizer capable of self analysis to determine it's grammar structure
* This is used for more advanced features requiring such information.
* for example: Error Recovery, Automatic lookahead calculation
*/
export class Parser {
static IGNORE_AMBIGUITIES:boolean = true
static NO_RESYNC:boolean = false
// Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected.
// (normally during the parser's constructor).
// This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors,
// for example: duplicate rule names, referencing an unresolved subrule, ect...
// This flag should not be enabled during normal usage, it is used in special situations, for example when
// needing to display the parser definition errors in some GUI(online playground).
static DEFER_DEFINITION_ERRORS_HANDLING:boolean = false
protected static performSelfAnalysis(classInstance:Parser) {
let definitionErrors = []
let defErrorsMsgs
let className = classNameFromInstance(classInstance)
if (className === "") {
// just a simple "throw Error" without any fancy "definition error" because the logic below relies on a unique parser name to
// save/access those definition errors...
throw Error("A Parser's constructor may not be an anonymous Function, it must be a named function\n" +
"The constructor's name is used at runtime for performance (caching) purposes.")
}
// this information should only be computed once
if (!cache.CLASS_TO_SELF_ANALYSIS_DONE.containsKey(className)) {
let grammarProductions = cache.getProductionsForClass(className)
// assumes this cache has been initialized (in the relevant parser's constructor)
// TODO: consider making the self analysis a member method to resolve this.
// that way it won't be callable before the constructor has been invoked...
definitionErrors = cache.CLASS_TO_DEFINITION_ERRORS.get(className)
let resolverErrors = resolveGrammar(grammarProductions)
definitionErrors.push.apply(definitionErrors, resolverErrors) // mutability for the win?
cache.CLASS_TO_SELF_ANALYSIS_DONE.put(className, true)
let validationErrors = validateGrammar(grammarProductions.values())
definitionErrors.push.apply(definitionErrors, validationErrors) // mutability for the win?
if (!isEmpty(definitionErrors) && !Parser.DEFER_DEFINITION_ERRORS_HANDLING) {
defErrorsMsgs = map(definitionErrors, defError => defError.message)
throw new Error(`Parser Definition Errors detected\n: ${defErrorsMsgs.join("\n-------------------------------\n")}`)
}
if (isEmpty(definitionErrors)) { // this analysis may fail if the grammar is not perfectly valid
let allFollows = computeAllProdsFollows(grammarProductions.values())
cache.setResyncFollowsForClass(className, allFollows)
}
}
// reThrow the validation errors each time an erroneous parser is instantiated
if (!isEmpty(cache.CLASS_TO_DEFINITION_ERRORS.get(className)) && !Parser.DEFER_DEFINITION_ERRORS_HANDLING) {
defErrorsMsgs = map(cache.CLASS_TO_DEFINITION_ERRORS.get(className), defError => defError.message)
throw new Error(`Parser Definition Errors detected\n: ${defErrorsMsgs.join("\n-------------------------------\n")}`)
}
}
public errors:exceptions.IRecognitionException[] = []
/**
* This flag enables or disables error recovery (fault tolerance) of the parser.
* If this flag is disabled the parser will halt on the first error.
*/
// TODO: should this become protected? and / or replaced with an IParserConfig object?
public recoveryEnabled
protected _input:Token[] = []
protected inputIdx = -1
protected isBackTrackingStack = []
protected className:string
protected RULE_STACK:string[] = []
protected RULE_OCCURRENCE_STACK:number[] = []
protected tokensMap:{ [fqn:string]:Function } = undefined
private firstAfterRepMap
private classLAFuncs
private definitionErrors:IParserDefinitionError[]
private orLookaheadKeys:HashTable<string>[]
private manyLookaheadKeys:HashTable<string>[]
private manySepLookaheadKeys:HashTable<string>[]
private atLeastOneSepLookaheadKeys:HashTable<string>[]
private atLeastOneLookaheadKeys:HashTable<string>[]
private optionLookaheadKeys:HashTable<string>[]
private definedRulesNames:string[] = []
constructor(input:Token[], tokensMapOrArr:{ [fqn:string]:Function; } | Function[],
config:IParserConfig = DEFAULT_PARSER_CONFIG) {
this._input = input
this.recoveryEnabled = has(config, "recoveryEnabled") ? config.recoveryEnabled : DEFAULT_PARSER_CONFIG.recoveryEnabled
this.className = classNameFromInstance(this)
this.firstAfterRepMap = cache.getFirstAfterRepForClass(this.className)
this.classLAFuncs = cache.getLookaheadFuncsForClass(this.className)
if (!cache.CLASS_TO_DEFINITION_ERRORS.containsKey(this.className)) {
this.definitionErrors = []
cache.CLASS_TO_DEFINITION_ERRORS.put(this.className, this.definitionErrors)
}
else {
this.definitionErrors = cache.CLASS_TO_DEFINITION_ERRORS.get(this.className)
}
if (isArray(tokensMapOrArr)) {
this.tokensMap = <any>reduce(<any>tokensMapOrArr, (acc, tokenClazz:Function) => {
acc[tokenName(tokenClazz)] = tokenClazz
return acc
}, {})
}
else if (isObject(tokensMapOrArr)) {
this.tokensMap = cloneObj(tokensMapOrArr)
}
else {
throw new Error("'tokensMapOrArr' argument must be An Array of Token constructors or a Dictionary of Tokens.")
}
// always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been
// parsed with a clear error message ("expecting EOF but found ...")
this.tokensMap[tokenName(EOF)] = EOF
if (cache.CLASS_TO_OR_LA_CACHE[this.className] === undefined) {
cache.initLookAheadKeyCache(this.className)
}
this.orLookaheadKeys = cache.CLASS_TO_OR_LA_CACHE[this.className]
this.manyLookaheadKeys = cache.CLASS_TO_MANY_LA_CACHE[this.className]
this.manySepLookaheadKeys = cache.CLASS_TO_MANY_SEP_LA_CACHE[this.className]
this.atLeastOneLookaheadKeys = cache.CLASS_TO_AT_LEAST_ONE_LA_CACHE[this.className]
this.atLeastOneSepLookaheadKeys = cache.CLASS_TO_AT_LEAST_ONE_SEP_LA_CACHE[this.className]
this.optionLookaheadKeys = cache.CLASS_TO_OPTION_LA_CACHE[this.className]
}
public set input(newInput:Token[]) {
this.reset()
this._input = newInput
}
public get input():Token[] {
return cloneArr(this._input)
}
public reset():void {
this.isBackTrackingStack = []
this.errors = []
this._input = []
this.inputIdx = -1
this.RULE_STACK = []
this.RULE_OCCURRENCE_STACK = []
}
public isAtEndOfInput():boolean {
return this.LA(1) instanceof EOF
}
public getGAstProductions():HashTable<gast.Rule> {
return cache.getProductionsForClass(this.className)
}
protected isBackTracking():boolean {
return !(isEmpty(this.isBackTrackingStack))
}
protected SAVE_ERROR(error:exceptions.IRecognitionException):exceptions.IRecognitionException {
if (exceptions.isRecognitionException(error)) {
error.context = {
ruleStack: cloneArr(this.RULE_STACK),
ruleOccurrenceStack: cloneArr(this.RULE_OCCURRENCE_STACK)
}
this.errors.push(error)
return error
}
else {
throw Error("Trying to save an Error which is not a RecognitionException")
}
}
protected NEXT_TOKEN():Token {
return this.LA(1)
}
protected LA(howMuch:number):Token {
if (this._input.length <= this.inputIdx + howMuch) {
return new EOF()
}
else {
return this._input[this.inputIdx + howMuch]
}
}
protected isNextRule<T>(ruleName:string):boolean {
let classLAFuncs = cache.getLookaheadFuncsForClass(this.className)
let condition = <any>classLAFuncs.get(ruleName)
if (condition === undefined) {
let ruleGrammar = this.getGAstProductions().get(ruleName)
condition = buildLookaheadForTopLevel(ruleGrammar)
classLAFuncs.put(ruleName, condition)
}
return condition.call(this)
}
/**
*
* @param grammarRule the rule to try and parse in backtracking mode
* @param isValid a predicate that given the result of the parse attempt will "decide" if the parse was successfully or not
* @return a lookahead function that will try to parse the given grammarRule and will return true if succeed
*/
protected BACKTRACK<T>(grammarRule:(...args) => T, isValid:(T) => boolean):() => boolean {
return () => {
// save org state
this.isBackTrackingStack.push(1)
let orgState = this.saveRecogState()
try {
let ruleResult = grammarRule.call(this)
return isValid(ruleResult)
} catch (e) {
if (exceptions.isRecognitionException(e)) {
return false
}
else {
throw e
}
}
finally {
this.reloadRecogState(orgState)
this.isBackTrackingStack.pop()
}
}
}
// skips a token and returns the next token
protected SKIP_TOKEN():Token {
// example: assume 45 tokens in the input, if input index is 44 it means that NEXT_TOKEN will return
// input[45] which is the 46th item and no longer exists,
// so in this case the largest valid input index is 43 (input.length - 2 )
if (this.inputIdx <= this._input.length - 2) {
this.inputIdx++
return this.NEXT_TOKEN()
}
else {
return new EOF()
}
}
// Parsing DSL
/**
* Convenience method equivalent to CONSUME1
* @see CONSUME1
*/
protected CONSUME(tokClass:Function):Token {
return this.CONSUME1(tokClass)
}
/**
*
* A Parsing DSL method use to consume a single terminal Token.
* a Token will be consumed, IFF the next token in the token vector is an instanceof tokClass.
* otherwise the parser will attempt to perform error recovery.
*
* The index in the method name indicates the unique occurrence of a terminal consumption
* inside a the top level rule. What this means is that if a terminal appears
* more than once in a single rule, each appearance must have a difference index.
*
* for example:
*
* function parseQualifiedName() {
* this.CONSUME1(Identifier);
* this.MANY(()=> {
* this.CONSUME1(Dot);
* this.CONSUME2(Identifier); // <-- here we use CONSUME2 because the terminal
* }); // 'Identifier' has already appeared previously in the
* // the rule 'parseQualifiedName'
* }
*
* @param {Function} tokClass A constructor function specifying the type of token
* to be consumed.
*
* @returns {Token} The consumed token.
*/
protected CONSUME1(tokClass:Function):Token {
return this.consumeInternal(tokClass, 1)
}
/**
* @see CONSUME1
*/
protected CONSUME2(tokClass:Function):Token {
return this.consumeInternal(tokClass, 2)
}
/**
* @see CONSUME1
*/
protected CONSUME3(tokClass:Function):Token {
return this.consumeInternal(tokClass, 3)
}
/**
* @see CONSUME1
*/
protected CONSUME4(tokClass:Function):Token {
return this.consumeInternal(tokClass, 4)
}
/**
* @see CONSUME1
*/
protected CONSUME5(tokClass:Function):Token {
return this.consumeInternal(tokClass, 5)
}
/**
* Convenience method equivalent to SUBRULE1
* @see SUBRULE1
*/
protected SUBRULE<T>(ruleToCall:(number) => T, args:any[] = []):T {
return this.SUBRULE1(ruleToCall, args)
}
/**
* The Parsing DSL Method is used by one rule to call another.
*
* This may seem redundant as it does not actually do much.
* However using it is mandatory for all sub rule invocations.
* calling another rule without wrapping in SUBRULE(...)
* will cause errors/mistakes in the Recognizer's self analysis
* which will lead to errors in error recovery/automatic lookahead calculation
* and any other functionality relying on the Recognizer's self analysis
* output.
*
* As in CONSUME the index in the method name indicates the occurrence
* of the sub rule invocation in its rule.
*
* @param {Function} ruleToCall the rule to invoke
* @param {*[]} args the arguments to pass to the invoked subrule
* @returns {*} the result of invoking ruleToCall
*/
protected SUBRULE1<T>(ruleToCall:(number) => T, args:any[] = []):T {
return ruleToCall.call(this, 1, args)
}
/**
* @see SUBRULE1
*/
protected SUBRULE2<T>(ruleToCall:(number) => T, args:any[] = []):T {
return ruleToCall.call(this, 2, args)
}
/**
* @see SUBRULE1
*/
protected SUBRULE3<T>(ruleToCall:(number) => T, args:any[] = []):T {
return ruleToCall.call(this, 3, args)
}
/**
* @see SUBRULE1
*/
protected SUBRULE4<T>(ruleToCall:(number) => T, args:any[] = []):T {
return ruleToCall.call(this, 4, args)
}
/**
* @see SUBRULE1
*/
protected SUBRULE5<T>(ruleToCall:(number) => T, args:any[] = []):T {
return ruleToCall.call(this, 5, args)
}
/**
* Convenience method equivalent to OPTION1
* @see OPTION1
*/
protected OPTION(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
return this.OPTION1.call(this, laFuncOrAction, action)
}
/**
* Parsing DSL Method that Indicates an Optional production
* in EBNF notation: [...]
*
* note that the 'action' param is optional. so both of the following forms are valid:
*
* short: this.OPTION(()=>{ this.CONSUME(Digit});
* long: this.OPTION(isDigit, ()=>{ this.CONSUME(Digit});
*
* using the short form is recommended as it will compute the lookahead function
* automatically. however this currently has one limitation:
* It only works if the lookahead for the grammar is one.
*
* As in CONSUME the index in the method name indicates the occurrence
* of the optional production in it's top rule.
*
* @param {Function} laFuncOrAction The lookahead function that 'decides'
* whether or not the OPTION's action will be
* invoked or the action to optionally invoke
* @param {Function} [action] The action to optionally invoke.
*
* @returns {boolean} true iff the OPTION's action has been invoked
*/
protected OPTION1(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
if (action === undefined) {
action = <any>laFuncOrAction
laFuncOrAction = this.getLookaheadFuncForOption(1)
}
return this.optionInternal(<any>laFuncOrAction, <any>action)
}
/**
* @see OPTION1
*/
protected OPTION2(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
if (action === undefined) {
action = <any>laFuncOrAction
laFuncOrAction = this.getLookaheadFuncForOption(2)
}
return this.optionInternal(<any>laFuncOrAction, <any>action)
}
/**
* @see OPTION1
*/
protected OPTION3(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
if (action === undefined) {
action = <any>laFuncOrAction
laFuncOrAction = this.getLookaheadFuncForOption(3)
}
return this.optionInternal(<any>laFuncOrAction, <any>action)
}
/**
* @see OPTION1
*/
protected OPTION4(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
if (action === undefined) {
action = <any>laFuncOrAction
laFuncOrAction = this.getLookaheadFuncForOption(4)
}
return this.optionInternal(<any>laFuncOrAction, <any>action)
}
/**
* @see OPTION1
*/
protected OPTION5(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):boolean {
if (action === undefined) {
action = <any>laFuncOrAction
laFuncOrAction = this.getLookaheadFuncForOption(5)
}
return this.optionInternal(<any>laFuncOrAction, <any>action)
}
/**
* Convenience method equivalent to OR1
* @see OR1
*/
protected OR<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.OR1(alts, errMsgTypes, ignoreAmbiguities)
}
/**
* Parsing DSL method that indicates a choice between a set of alternatives must be made.
* This is equivalent to EBNF alternation (A | B | C | D ...)
*
* There are two forms:
*
* short: this.OR([
* {ALT:()=>{this.CONSUME(One)}},
* {ALT:()=>{this.CONSUME(Two)}},
* {ALT:()=>{this.CONSUME(Three)}},
* ], "a number")
*
* long: this.OR([
* {WHEN: isOne, THEN_DO:()=>{this.CONSUME(One)}},
* {WHEN: isTwo, THEN_DO:()=>{this.CONSUME(Two)}},
* {WHEN: isThree, THEN_DO:()=>{this.CONSUME(Three)}},
* ], "a number")
*
* using the short form is recommended as it will compute the lookahead function
* automatically. however this currently has one limitation:
* It only works if the lookahead for the grammar is one LL(1).
*
* As in CONSUME the index in the method name indicates the occurrence
* of the alternation production in it's top rule.
*
* @param {{ALT:Function}[] | {WHEN:Function, THEN_DO:Function}[]} alts - An array of alternatives
*
* @param {string} [errMsgTypes] - A description for the alternatives used in error messages
* If none is provided, the error message will include the names of the expected
* Tokens which may start each alternative.
*
* @param {boolean} [ignoreAmbiguities] - if true this will ignore ambiguities caused when two alternatives can not
* be distinguished by a lookahead of one. enabling this means the first alternative
* that matches will be taken. This is sometimes the grammar's intent.
* * only enable this if you know what you are doing!
*
* @returns {*} The result of invoking the chosen alternative
*/
protected OR1<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.orInternal(alts, errMsgTypes, 1, ignoreAmbiguities)
}
/**
* @see OR1
*/
protected OR2<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.orInternal(alts, errMsgTypes, 2, ignoreAmbiguities)
}
/**
* @see OR1
*/
protected OR3<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.orInternal(alts, errMsgTypes, 3, ignoreAmbiguities)
}
/**
* @see OR1
*/
protected OR4<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.orInternal(alts, errMsgTypes, 4, ignoreAmbiguities)
}
/**
* @see OR1
*/
protected OR5<T>(alts:IOrAlt<T>[] | IOrAltImplicit<T>[], errMsgTypes?:string, ignoreAmbiguities:boolean = false):T {
return this.orInternal(alts, errMsgTypes, 5, ignoreAmbiguities)
}
/**
* Convenience method equivalent to MANY1
* @see MANY1
*/
protected MANY(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
return this.MANY1.call(this, laFuncOrAction, action)
}
/**
* Parsing DSL method, that indicates a repetition of zero or more.
* This is equivalent to EBNF repetition {...}
*
* note that the 'action' param is optional. so both of the following forms are valid:
*
* short: this.MANY(()=>{
* this.CONSUME(Comma};
* this.CONSUME(Digit});
* long: this.MANY(isComma, ()=>{
* this.CONSUME(Comma};
* this.CONSUME(Digit});
*
* using the short form is recommended as it will compute the lookahead function
* automatically. however this currently has one limitation:
* It only works if the lookahead for the grammar is one.
*
* As in CONSUME the index in the method name indicates the occurrence
* of the repetition production in it's top rule.
*
* @param {Function} laFuncOrAction The lookahead function that 'decides'
* whether or not the MANY's action will be
* invoked or the action to optionally invoke
* @param {Function} [action] The action to optionally invoke.
*/
protected MANY1(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
this.manyInternal(this.MANY1, "MANY1", 1, laFuncOrAction, action)
}
/**
* @see MANY1
*/
protected MANY2(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
this.manyInternal(this.MANY2, "MANY2", 2, laFuncOrAction, action)
}
/**
* @see MANY1
*/
protected MANY3(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
this.manyInternal(this.MANY3, "MANY3", 3, laFuncOrAction, action)
}
/**
* @see MANY1
*/
protected MANY4(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
this.manyInternal(this.MANY4, "MANY4", 4, laFuncOrAction, action)
}
/**
* @see MANY1
*/
protected MANY5(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):void {
this.manyInternal(this.MANY5, "MANY5", 5, laFuncOrAction, action)
}
/**
* Convenience method equivalent to MANY_SEP1
* @see MANY_SEP1
*/
protected MANY_SEP(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.MANY_SEP1.call(this, separator, laFuncOrAction, action)
}
/**
* Parsing DSL method, that indicates a repetition of zero or more with a separator
* Token between the repetitions.
*
* note that the 'action' param is optional. so both of the following forms are valid:
*
* short: this.MANY_SEP(Comma, ()=>{
* this.CONSUME(Number};
* ...
* );
*
* long: this.MANY(Comma, isNumber, ()=>{
* this.CONSUME(Number}
* ...
* );
*
* using the short form is recommended as it will compute the lookahead function
* (for the first iteration) automatically. however this currently has one limitation:
* It only works if the lookahead for the grammar is one.
*
* As in CONSUME the index in the method name indicates the occurrence
* of the repetition production in it's top rule.
*
* @param separator - The Token to use as a separator between repetitions.
* @param {Function} laFuncOrAction - The lookahead function that 'decides'
* whether or not the MANY_SEP's action will be
* invoked or the action to optionally invoke
* @param {Function} [action] - The action to optionally invoke.
*
* @return {Token[]} - The consumed separator Tokens.
*/
protected MANY_SEP1(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.manySepFirstInternal(this.MANY_SEP1, "MANY_SEP1", 1, separator, laFuncOrAction, action)
}
/**
* @see MANY_SEP1
*/
protected MANY_SEP2(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.manySepFirstInternal(this.MANY_SEP2, "MANY_SEP2", 2, separator, laFuncOrAction, action)
}
/**
* @see MANY_SEP1
*/
protected MANY_SEP3(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.manySepFirstInternal(this.MANY_SEP3, "MANY_SEP3", 3, separator, laFuncOrAction, action)
}
/**
* @see MANY_SEP1
*/
protected MANY_SEP4(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.manySepFirstInternal(this.MANY_SEP4, "MANY_SEP4", 4, separator, laFuncOrAction, action)
}
/**
* @see MANY_SEP1
*/
protected MANY_SEP5(separator:TokenConstructor, laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction):Token[] {
return this.manySepFirstInternal(this.MANY_SEP5, "MANY_SEP5", 5, separator, laFuncOrAction, action)
}
/**
* Convenience method equivalent to AT_LEAST_ONE1
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
return this.AT_LEAST_ONE1.call(this, laFuncOrAction, action, errMsg)
}
/**
*
* convenience method, same as MANY but the repetition is of one or more.
* failing to match at least one repetition will result in a parsing error and
* cause the parser to attempt error recovery.
*
* @see MANY1
*
* @param {Function} laFuncOrAction The lookahead function that 'decides'
* whether or not the AT_LEAST_ONE's action will be
* invoked or the action to optionally invoke
* @param {Function} [action] The action to optionally invoke.
* @param {string} [errMsg] short title/classification to what is being matched
*/
protected AT_LEAST_ONE1(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
this.atLeastOneInternal(this.AT_LEAST_ONE1, "AT_LEAST_ONE1", 1, laFuncOrAction, action, errMsg)
}
/**
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE2(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
this.atLeastOneInternal(this.AT_LEAST_ONE2, "AT_LEAST_ONE2", 2, laFuncOrAction, action, errMsg)
}
/**
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE3(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
this.atLeastOneInternal(this.AT_LEAST_ONE3, "AT_LEAST_ONE3", 3, laFuncOrAction, action, errMsg)
}
/**
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE4(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
this.atLeastOneInternal(this.AT_LEAST_ONE4, "AT_LEAST_ONE4", 4, laFuncOrAction, action, errMsg)
}
/**
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE5(laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):void {
this.atLeastOneInternal(this.AT_LEAST_ONE5, "AT_LEAST_ONE5", 5, laFuncOrAction, action, errMsg)
}
/**
* Convenience method equivalent to AT_LEAST_ONE_SEP1
* @see AT_LEAST_ONE1
*/
protected AT_LEAST_ONE_SEP(separator:TokenConstructor,
laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):Token[] {
return this.AT_LEAST_ONE_SEP1.call(this, separator, laFuncOrAction, action, errMsg)
}
/**
*
* convenience method, same as MANY_SEP but the repetition is of one or more.
* failing to match at least one repetition will result in a parsing error and
* cause the parser to attempt error recovery.
*
* @see MANY_SEP1
*
* @param separator {Token}
* @param {Function} laFuncOrAction The lookahead function that 'decides'
* whether or not the AT_LEAST_ONE's action will be
* invoked or the action to optionally invoke
* @param {Function} [action] The action to optionally invoke.
* @param {string} [errMsg] short title/classification to what is being matched
*/
protected AT_LEAST_ONE_SEP1(separator:TokenConstructor,
laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):Token[] {
return this.atLeastOneSepFirstInternal(this.atLeastOneSepFirstInternal, "AT_LEAST_ONE_SEP1", 1, separator,
laFuncOrAction, action, errMsg)
}
/**
* @see AT_LEAST_ONE_SEP1
*/
protected AT_LEAST_ONE_SEP2(separator:TokenConstructor,
laFuncOrAction:LookAheadFunc | GrammarAction,
action?:GrammarAction | string,
errMsg?:string):Token[] {