This repository has been archived by the owner on Jun 15, 2019. It is now read-only.
forked from zaach/jison-lex
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathregexp-lexer.js
3124 lines (2780 loc) · 116 KB
/
regexp-lexer.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
// Basic Lexer implemented using JavaScript regular expressions
// Zachary Carter <[email protected]>
// MIT Licensed
import XRegExp from '@gerhobbelt/xregexp';
import json5 from '@gerhobbelt/json5';
import lexParser from '@gerhobbelt/lex-parser';
import setmgmt from './regexp-set-management.js';
import helpers from 'jison-helpers-lib';
var rmCommonWS = helpers.rmCommonWS;
var camelCase = helpers.camelCase;
var code_exec = helpers.exec;
// import recast from '@gerhobbelt/recast';
// import astUtils from '@gerhobbelt/ast-util';
import assert from 'assert';
var version = '0.6.1-208'; // require('./package.json').version;
const XREGEXP_UNICODE_ESCAPE_RE = setmgmt.XREGEXP_UNICODE_ESCAPE_RE; // Matches the XRegExp Unicode escape braced part, e.g. `{Number}`
const CHR_RE = setmgmt.CHR_RE;
const SET_PART_RE = setmgmt.SET_PART_RE;
const NOTHING_SPECIAL_RE = setmgmt.NOTHING_SPECIAL_RE;
const UNICODE_BASE_PLANE_MAX_CP = setmgmt.UNICODE_BASE_PLANE_MAX_CP;
// The expanded regex sets which are equivalent to the given `\\{c}` escapes:
//
// `/\s/`:
const WHITESPACE_SETSTR = setmgmt.WHITESPACE_SETSTR;
// `/\d/`:
const DIGIT_SETSTR = setmgmt.DIGIT_SETSTR;
// `/\w/`:
const WORDCHAR_SETSTR = setmgmt.WORDCHAR_SETSTR;
// WARNING: this regex MUST match the regex for `ID` in ebnf-parser::bnf.l jison language lexer spec! (`ID = [{ALPHA}]{ALNUM}*`)
//
// This is the base XRegExp ID regex used in many places; this should match the ID macro definition in the EBNF/BNF parser et al as well!
const ID_REGEX_BASE = '[\\p{Alphabetic}_][\\p{Alphabetic}_\\p{Number}]*';
// see also ./lib/cli.js
/**
@public
@nocollapse
*/
const defaultJisonLexOptions = {
moduleType: 'commonjs',
debug: false,
enableDebugLogs: false,
json: false,
main: false, // CLI: not:(--main option)
dumpSourceCodeOnFailure: true,
throwErrorOnCompileFailure: true,
moduleName: undefined,
defaultModuleName: 'lexer',
file: undefined,
outfile: undefined,
inputPath: undefined,
inputFilename: undefined,
warn_cb: undefined, // function(msg) | true (= use Jison.Print) | false (= throw Exception)
xregexp: false,
lexerErrorsAreRecoverable: false,
flex: false,
backtrack_lexer: false,
ranges: false, // track position range, i.e. start+end indexes in the input string
trackPosition: true, // track line+column position in the input string
caseInsensitive: false,
showSource: false,
exportSourceCode: false,
exportAST: false,
prettyCfg: true,
pre_lex: undefined,
post_lex: undefined,
};
// Merge sets of options.
//
// Convert alternative jison option names to their base option.
//
// The *last* option set which overrides the default wins, where 'override' is
// defined as specifying a not-undefined value which is not equal to the
// default value.
//
// When the FIRST argument is STRING "NODEFAULT", then we MUST NOT mix the
// default values avialable in Jison.defaultJisonOptions.
//
// Return a fresh set of options.
/** @public */
function mkStdOptions(/*...args*/) {
var h = Object.prototype.hasOwnProperty;
var opts = {};
var args = [].concat.apply([], arguments);
// clone defaults, so we do not modify those constants?
if (args[0] !== "NODEFAULT") {
args.unshift(defaultJisonLexOptions);
} else {
args.shift();
}
for (var i = 0, len = args.length; i < len; i++) {
var o = args[i];
if (!o) continue;
// clone input (while camel-casing the options), so we do not modify those either.
var o2 = {};
for (var p in o) {
if (typeof o[p] !== 'undefined' && h.call(o, p)) {
o2[camelCase(p)] = o[p];
}
}
// now clean them options up:
if (typeof o2.main !== 'undefined') {
o2.noMain = !o2.main;
}
delete o2.main;
// special check for `moduleName` to ensure we detect the 'default' moduleName entering from the CLI
// NOT overriding the moduleName set in the grammar definition file via an `%options` entry:
if (o2.moduleName === o2.defaultModuleName) {
delete o2.moduleName;
}
// now see if we have an overriding option here:
for (var p in o2) {
if (h.call(o2, p)) {
if (typeof o2[p] !== 'undefined') {
opts[p] = o2[p];
}
}
}
}
return opts;
}
// set up export/output attributes of the `options` object instance
function prepExportStructures(options) {
// set up the 'option' `exportSourceCode` as a hash object for returning
// all generated source code chunks to the caller
var exportSourceCode = options.exportSourceCode;
if (!exportSourceCode || typeof exportSourceCode !== 'object') {
exportSourceCode = {
enabled: !!exportSourceCode
};
} else if (typeof exportSourceCode.enabled !== 'boolean') {
exportSourceCode.enabled = true;
}
options.exportSourceCode = exportSourceCode;
}
// Autodetect if the input lexer spec is in JSON or JISON
// format when the `options.json` flag is `true`.
//
// Produce the JSON lexer spec result when these are JSON formatted already as that
// would save us the trouble of doing this again, anywhere else in the JISON
// compiler/generator.
//
// Otherwise return the *parsed* lexer spec as it has
// been processed through LexParser.
function autodetectAndConvertToJSONformat(lexerSpec, options) {
var chk_l = null;
var ex1, err;
if (typeof lexerSpec === 'string') {
if (options.json) {
try {
chk_l = json5.parse(lexerSpec);
// When JSON5-based parsing of the lexer spec succeeds, this implies the lexer spec is specified in `JSON mode`
// *OR* there's a JSON/JSON5 format error in the input:
} catch (e) {
ex1 = e;
}
}
if (!chk_l) {
// // WARNING: the lexer may receive options specified in the **grammar spec file**,
// // hence we should mix the options to ensure the lexParser always
// // receives the full set!
// //
// // make sure all options are 'standardized' before we go and mix them together:
// options = mkStdOptions(grammar.options, options);
try {
chk_l = lexParser.parse(lexerSpec, options);
} catch (e) {
if (options.json) {
err = new Error('Could not parse lexer spec in JSON AUTODETECT mode\nError: ' + ex1.message + ' (' + e.message + ')');
err.secondary_exception = e;
err.stack = ex1.stack;
} else {
err = new Error('Could not parse lexer spec\nError: ' + e.message);
err.stack = e.stack;
}
throw err;
}
}
} else {
chk_l = lexerSpec;
}
// Save time! Don't reparse the entire lexer spec *again* inside the code generators when that's not necessary:
return chk_l;
}
// expand macros and convert matchers to RegExp's
function prepareRules(dict, actions, caseHelper, tokens, startConditions, opts) {
var m, i, k, rule, action, conditions,
active_conditions,
rules = dict.rules || [],
newRules = [],
macros = {},
regular_rule_count = 0,
simple_rule_count = 0;
// Assure all options are camelCased:
assert(typeof opts.options['case-insensitive'] === 'undefined');
if (!tokens) {
tokens = {};
}
// Depending on the location within the regex we need different expansions of the macros:
// one expansion for when a macro is *inside* a `[...]` and another expansion when a macro
// is anywhere else in a regex:
if (dict.macros) {
macros = prepareMacros(dict.macros, opts);
}
function tokenNumberReplacement(str, token) {
return 'return ' + (tokens[token] || '\'' + token.replace(/'/g, '\\\'') + '\'');
}
// Make sure a comment does not contain any embedded '*/' end-of-comment marker
// as that would break the generated code
function postprocessComment(str) {
if (Array.isArray(str)) {
str = str.join(' ');
}
str = str.replace(/\*\//g, '*\\/'); // destroy any inner `*/` comment terminator sequence.
return str;
}
actions.push('switch(yyrulenumber) {');
for (i = 0; i < rules.length; i++) {
rule = rules[i];
m = rule[0];
active_conditions = [];
if (Object.prototype.toString.apply(m) !== '[object Array]') {
// implicit add to all inclusive start conditions
for (k in startConditions) {
if (startConditions[k].inclusive) {
active_conditions.push(k);
startConditions[k].rules.push(i);
}
}
} else if (m[0] === '*') {
// Add to ALL start conditions
active_conditions.push('*');
for (k in startConditions) {
startConditions[k].rules.push(i);
}
rule.shift();
m = rule[0];
} else {
// Add to explicit start conditions
conditions = rule.shift();
m = rule[0];
for (k = 0; k < conditions.length; k++) {
if (!startConditions.hasOwnProperty(conditions[k])) {
startConditions[conditions[k]] = {
rules: [],
inclusive: false
};
console.warn('Lexer Warning:', '"' + conditions[k] + '" start condition should be defined as %s or %x; assuming %x now.');
}
active_conditions.push(conditions[k]);
startConditions[conditions[k]].rules.push(i);
}
}
if (typeof m === 'string') {
m = expandMacros(m, macros, opts);
m = new XRegExp('^(?:' + m + ')', opts.options.caseInsensitive ? 'i' : '');
}
newRules.push(m);
if (typeof rule[1] === 'function') {
rule[1] = String(rule[1]).replace(/^\s*function \(\)\s?\{/, '').replace(/\}\s*$/, '');
}
action = rule[1];
action = action.replace(/return '((?:\\'|[^']+)+)'/g, tokenNumberReplacement);
action = action.replace(/return "((?:\\"|[^"]+)+)"/g, tokenNumberReplacement);
var code = ['\n/*! Conditions::'];
code.push(postprocessComment(active_conditions));
code.push('*/', '\n/*! Rule:: ');
code.push(postprocessComment(rules[i][0]));
code.push('*/', '\n');
// When the action is *only* a simple `return TOKEN` statement, then add it to the caseHelpers;
// otherwise add the additional `break;` at the end.
//
// Note: we do NOT analyze the action block any more to see if the *last* line is a simple
// `return NNN;` statement as there are too many shoddy idioms, e.g.
//
// ```
// %{ if (cond)
// return TOKEN;
// %}
// ```
//
// which would then cause havoc when our action code analysis (using regexes or otherwise) was 'too simple'
// to catch these culprits; hence we resort and stick with the most fundamental approach here:
// always append `break;` even when it would be obvious to a human that such would be 'unreachable code'.
var match_nr = /^return[\s\r\n]+((?:'(?:\\'|[^']+)+')|(?:"(?:\\"|[^"]+)+")|\d+)[\s\r\n]*;?$/.exec(action.trim());
if (match_nr) {
simple_rule_count++;
caseHelper.push([].concat(code, i, ':', match_nr[1]).join(' ').replace(/[\n]/g, '\n '));
} else {
regular_rule_count++;
actions.push([].concat('case', i, ':', code, action, '\nbreak;').join(' '));
}
}
actions.push('default:');
actions.push(' return this.simpleCaseActionClusters[yyrulenumber];');
actions.push('}');
return {
rules: newRules,
macros: macros,
regular_rule_count: regular_rule_count,
simple_rule_count: simple_rule_count,
};
}
// expand all macros (with maybe one exception) in the given regex: the macros may exist inside `[...]` regex sets or
// elsewhere, which requires two different treatments to expand these macros.
function reduceRegex(s, name, opts, expandAllMacrosInSet_cb, expandAllMacrosElsewhere_cb) {
var orig = s;
function errinfo() {
if (name) {
return 'macro [[' + name + ']]';
} else {
return 'regex [[' + orig + ']]';
}
}
// propagate deferred exceptions = error reports.
if (s instanceof Error) {
return s;
}
var c1, c2;
var rv = [];
var derr;
var se;
while (s.length) {
c1 = s.match(CHR_RE);
if (!c1) {
// cope with illegal escape sequences too!
return new Error(errinfo() + ': illegal escape sequence at start of regex part: ' + s);
} else {
c1 = c1[0];
}
s = s.substr(c1.length);
switch (c1) {
case '[':
// this is starting a set within the regex: scan until end of set!
var set_content = [];
var l = new Array(UNICODE_BASE_PLANE_MAX_CP + 1);
while (s.length) {
var inner = s.match(SET_PART_RE);
if (!inner) {
inner = s.match(CHR_RE);
if (!inner) {
// cope with illegal escape sequences too!
return new Error(errinfo() + ': illegal escape sequence at start of regex part: ' + s);
} else {
inner = inner[0];
}
if (inner === ']') break;
} else {
inner = inner[0];
}
set_content.push(inner);
s = s.substr(inner.length);
}
// ensure that we hit the terminating ']':
c2 = s.match(CHR_RE);
if (!c2) {
// cope with illegal escape sequences too!
return new Error(errinfo() + ': regex set expression is broken: "' + s + '"');
} else {
c2 = c2[0];
}
if (c2 !== ']') {
return new Error(errinfo() + ': regex set expression is broken: apparently unterminated');
}
s = s.substr(c2.length);
se = set_content.join('');
// expand any macros in here:
if (expandAllMacrosInSet_cb) {
se = expandAllMacrosInSet_cb(se);
assert(se);
if (se instanceof Error) {
return new Error(errinfo() + ': ' + se.message);
}
}
derr = setmgmt.set2bitarray(l, se, opts);
if (derr instanceof Error) {
return new Error(errinfo() + ': ' + derr.message);
}
// find out which set expression is optimal in size:
var s1 = setmgmt.produceOptimizedRegex4Set(l);
// check if the source regex set potentially has any expansions (guestimate!)
//
// The indexOf('{') picks both XRegExp Unicode escapes and JISON lexer macros, which is perfect for us here.
var has_expansions = (se.indexOf('{') >= 0);
se = '[' + se + ']';
if (!has_expansions && se.length < s1.length) {
s1 = se;
}
rv.push(s1);
break;
// XRegExp Unicode escape, e.g. `\\p{Number}`:
case '\\p':
c2 = s.match(XREGEXP_UNICODE_ESCAPE_RE);
if (c2) {
c2 = c2[0];
s = s.substr(c2.length);
// nothing to expand.
rv.push(c1 + c2);
} else {
// nothing to stretch this match, hence nothing to expand.
rv.push(c1);
}
break;
// Either a range expression or the start of a macro reference: `.{1,3}` or `{NAME}`.
// Treat it as a macro reference and see if it will expand to anything:
case '{':
c2 = s.match(NOTHING_SPECIAL_RE);
if (c2) {
c2 = c2[0];
s = s.substr(c2.length);
var c3 = s[0];
s = s.substr(c3.length);
if (c3 === '}') {
// possibly a macro name in there... Expand if possible:
c2 = c1 + c2 + c3;
if (expandAllMacrosElsewhere_cb) {
c2 = expandAllMacrosElsewhere_cb(c2);
assert(c2);
if (c2 instanceof Error) {
return new Error(errinfo() + ': ' + c2.message);
}
}
} else {
// not a well-terminated macro reference or something completely different:
// we do not even attempt to expand this as there's guaranteed nothing to expand
// in this bit.
c2 = c1 + c2 + c3;
}
rv.push(c2);
} else {
// nothing to stretch this match, hence nothing to expand.
rv.push(c1);
}
break;
// Recognize some other regex elements, but there's no need to understand them all.
//
// We are merely interested in any chunks now which do *not* include yet another regex set `[...]`
// nor any `{MACRO}` reference:
default:
// non-set character or word: see how much of this there is for us and then see if there
// are any macros still lurking inside there:
c2 = s.match(NOTHING_SPECIAL_RE);
if (c2) {
c2 = c2[0];
s = s.substr(c2.length);
// nothing to expand.
rv.push(c1 + c2);
} else {
// nothing to stretch this match, hence nothing to expand.
rv.push(c1);
}
break;
}
}
s = rv.join('');
// When this result is suitable for use in a set, than we should be able to compile
// it in a regex; that way we can easily validate whether macro X is fit to be used
// inside a regex set:
try {
var re;
re = new XRegExp(s);
re.test(s[0]);
} catch (ex) {
// make sure we produce a regex expression which will fail badly when it is used
// in actual code:
return new Error(errinfo() + ': expands to an invalid regex: /' + s + '/');
}
assert(s);
return s;
}
// expand macros within macros and cache the result
function prepareMacros(dict_macros, opts) {
var macros = {};
// expand a `{NAME}` macro which exists inside a `[...]` set:
function expandMacroInSet(i) {
var k, a, m;
if (!macros[i]) {
m = dict_macros[i];
if (m.indexOf('{') >= 0) {
// set up our own record so we can detect definition loops:
macros[i] = {
in_set: false,
elsewhere: null,
raw: dict_macros[i]
};
for (k in dict_macros) {
if (dict_macros.hasOwnProperty(k) && i !== k) {
// it doesn't matter if the lexer recognized that the inner macro(s)
// were sitting inside a `[...]` set or not: the fact that they are used
// here in macro `i` which itself sits in a set, makes them *all* live in
// a set so all of them get the same treatment: set expansion style.
//
// Note: make sure we don't try to expand any XRegExp `\p{...}` or `\P{...}`
// macros here:
if (XRegExp._getUnicodeProperty(k)) {
// Work-around so that you can use `\p{ascii}` for a XRegExp slug, a.k.a.
// Unicode 'General Category' Property cf. http://unicode.org/reports/tr18/#Categories,
// while using `\p{ASCII}` as a *macro expansion* of the `ASCII`
// macro:
if (k.toUpperCase() !== k) {
m = new Error('Cannot use name "' + k + '" as a macro name as it clashes with the same XRegExp "\\p{..}" Unicode \'General Category\' Property name. Use all-uppercase macro names, e.g. name your macro "' + k.toUpperCase() + '" to work around this issue or give your offending macro a different name.');
break;
}
}
a = m.split('{' + k + '}');
if (a.length > 1) {
var x = expandMacroInSet(k);
assert(x);
if (x instanceof Error) {
m = x;
break;
}
m = a.join(x);
}
}
}
}
var mba = setmgmt.reduceRegexToSetBitArray(m, i, opts);
var s1;
// propagate deferred exceptions = error reports.
if (mba instanceof Error) {
s1 = mba;
} else {
s1 = setmgmt.bitarray2set(mba, false);
m = s1;
}
macros[i] = {
in_set: s1,
elsewhere: null,
raw: dict_macros[i]
};
} else {
m = macros[i].in_set;
if (m instanceof Error) {
// this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!
return new Error(m.message);
}
// detect definition loop:
if (m === false) {
return new Error('Macro name "' + i + '" has an illegal, looping, definition, i.e. it\'s definition references itself, either directly or indirectly, via other macros.');
}
}
return m;
}
function expandMacroElsewhere(i) {
var k, a, m;
if (macros[i].elsewhere == null) {
m = dict_macros[i];
// set up our own record so we can detect definition loops:
macros[i].elsewhere = false;
// the macro MAY contain other macros which MAY be inside a `[...]` set in this
// macro or elsewhere, hence we must parse the regex:
m = reduceRegex(m, i, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);
// propagate deferred exceptions = error reports.
if (m instanceof Error) {
return m;
}
macros[i].elsewhere = m;
} else {
m = macros[i].elsewhere;
if (m instanceof Error) {
// this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!
return m;
}
// detect definition loop:
if (m === false) {
return new Error('Macro name "' + i + '" has an illegal, looping, definition, i.e. it\'s definition references itself, either directly or indirectly, via other macros.');
}
}
return m;
}
function expandAllMacrosInSet(s) {
var i, x;
// process *all* the macros inside [...] set:
if (s.indexOf('{') >= 0) {
for (i in macros) {
if (macros.hasOwnProperty(i)) {
var a = s.split('{' + i + '}');
if (a.length > 1) {
x = expandMacroInSet(i);
assert(x);
if (x instanceof Error) {
return new Error('failure to expand the macro [' + i + '] in set [' + s + ']: ' + x.message);
}
s = a.join(x);
}
// stop the brute-force expansion attempt when we done 'em all:
if (s.indexOf('{') === -1) {
break;
}
}
}
}
return s;
}
function expandAllMacrosElsewhere(s) {
var i, x;
// When we process the remaining macro occurrences in the regex
// every macro used in a lexer rule will become its own capture group.
//
// Meanwhile the cached expansion will expand any submacros into
// *NON*-capturing groups so that the backreference indexes remain as you'ld
// expect and using macros doesn't require you to know exactly what your
// used macro will expand into, i.e. which and how many submacros it has.
//
// This is a BREAKING CHANGE from vanilla jison 0.4.15!
if (s.indexOf('{') >= 0) {
for (i in macros) {
if (macros.hasOwnProperty(i)) {
// These are all submacro expansions, hence non-capturing grouping is applied:
var a = s.split('{' + i + '}');
if (a.length > 1) {
x = expandMacroElsewhere(i);
assert(x);
if (x instanceof Error) {
return new Error('failure to expand the macro [' + i + '] in regex /' + s + '/: ' + x.message);
}
s = a.join('(?:' + x + ')');
}
// stop the brute-force expansion attempt when we done 'em all:
if (s.indexOf('{') === -1) {
break;
}
}
}
}
return s;
}
var m, i;
if (opts.debug) console.log('\n############## RAW macros: ', dict_macros);
// first we create the part of the dictionary which is targeting the use of macros
// *inside* `[...]` sets; once we have completed that half of the expansions work,
// we then go and expand the macros for when they are used elsewhere in a regex:
// iff we encounter submacros then which are used *inside* a set, we can use that
// first half dictionary to speed things up a bit as we can use those expansions
// straight away!
for (i in dict_macros) {
if (dict_macros.hasOwnProperty(i)) {
expandMacroInSet(i);
}
}
for (i in dict_macros) {
if (dict_macros.hasOwnProperty(i)) {
expandMacroElsewhere(i);
}
}
if (opts.debug) console.log('\n############### expanded macros: ', macros);
return macros;
}
// expand macros in a regex; expands them recursively
function expandMacros(src, macros, opts) {
var expansion_count = 0;
// By the time we call this function `expandMacros` we MUST have expanded and cached all macros already!
// Hence things should be easy in there:
function expandAllMacrosInSet(s) {
var i, m, x;
// process *all* the macros inside [...] set:
if (s.indexOf('{') >= 0) {
for (i in macros) {
if (macros.hasOwnProperty(i)) {
m = macros[i];
var a = s.split('{' + i + '}');
if (a.length > 1) {
x = m.in_set;
assert(x);
if (x instanceof Error) {
// this turns out to be an macro with 'issues' and it is used, so the 'issues' do matter: bombs away!
throw x;
}
// detect definition loop:
if (x === false) {
return new Error('Macro name "' + i + '" has an illegal, looping, definition, i.e. it\'s definition references itself, either directly or indirectly, via other macros.');
}
s = a.join(x);
expansion_count++;
}
// stop the brute-force expansion attempt when we done 'em all:
if (s.indexOf('{') === -1) {
break;
}
}
}
}
return s;
}
function expandAllMacrosElsewhere(s) {
var i, m, x;
// When we process the main macro occurrences in the regex
// every macro used in a lexer rule will become its own capture group.
//
// Meanwhile the cached expansion will expand any submacros into
// *NON*-capturing groups so that the backreference indexes remain as you'ld
// expect and using macros doesn't require you to know exactly what your
// used macro will expand into, i.e. which and how many submacros it has.
//
// This is a BREAKING CHANGE from vanilla jison 0.4.15!
if (s.indexOf('{') >= 0) {
for (i in macros) {
if (macros.hasOwnProperty(i)) {
m = macros[i];
var a = s.split('{' + i + '}');
if (a.length > 1) {
// These are all main macro expansions, hence CAPTURING grouping is applied:
x = m.elsewhere;
assert(x);
// detect definition loop:
if (x === false) {
return new Error('Macro name "' + i + '" has an illegal, looping, definition, i.e. it\'s definition references itself, either directly or indirectly, via other macros.');
}
s = a.join('(' + x + ')');
expansion_count++;
}
// stop the brute-force expansion attempt when we done 'em all:
if (s.indexOf('{') === -1) {
break;
}
}
}
}
return s;
}
// When we process the macro occurrences in the regex
// every macro used in a lexer rule will become its own capture group.
//
// Meanwhile the cached expansion will have expanded any submacros into
// *NON*-capturing groups so that the backreference indexes remain as you'ld
// expect and using macros doesn't require you to know exactly what your
// used macro will expand into, i.e. which and how many submacros it has.
//
// This is a BREAKING CHANGE from vanilla jison 0.4.15!
var s2 = reduceRegex(src, null, opts, expandAllMacrosInSet, expandAllMacrosElsewhere);
// propagate deferred exceptions = error reports.
if (s2 instanceof Error) {
throw s2;
}
// only when we did expand some actual macros do we take the re-interpreted/optimized/regenerated regex from reduceRegex()
// in order to keep our test cases simple and rules recognizable. This assumes the user can code good regexes on his own,
// as long as no macros are involved...
//
// Also pick the reduced regex when there (potentially) are XRegExp extensions in the original, e.g. `\\p{Number}`,
// unless the `xregexp` output option has been enabled.
if (expansion_count > 0 || (src.indexOf('\\p{') >= 0 && !opts.options.xregexp)) {
src = s2;
} else {
// Check if the reduced regex is smaller in size; when it is, we still go with the new one!
if (s2.length < src.length) {
src = s2;
}
}
return src;
}
function prepareStartConditions(conditions) {
var sc,
hash = {};
for (sc in conditions) {
if (conditions.hasOwnProperty(sc)) {
hash[sc] = {rules:[], inclusive: !conditions[sc]};
}
}
return hash;
}
function buildActions(dict, tokens, opts) {
var actions = [dict.actionInclude || '', 'var YYSTATE = YY_START;'];
var tok;
var toks = {};
var caseHelper = [];
// tokens: map/array of token numbers to token names
for (tok in tokens) {
var idx = parseInt(tok);
if (idx && idx > 0) {
toks[tokens[tok]] = idx;
}
}
if (opts.options.flex && dict.rules) {
dict.rules.push(['.', 'console.log("", yytext); /* `flex` lexing mode: the last resort rule! */']);
}
var gen = prepareRules(dict, actions, caseHelper, tokens && toks, opts.conditions, opts);
var fun = actions.join('\n');
'yytext yyleng yylineno yylloc yyerror'.split(' ').forEach(function (yy) {
fun = fun.replace(new RegExp('\\b(' + yy + ')\\b', 'g'), 'yy_.$1');
});
return {
caseHelperInclude: '{\n' + caseHelper.join(',') + '\n}',
actions: `function lexer__performAction(yy, yyrulenumber, YY_START) {
var yy_ = this;
${fun}
}`,
rules: gen.rules,
macros: gen.macros, // propagate these for debugging/diagnostic purposes
regular_rule_count: gen.regular_rule_count,
simple_rule_count: gen.simple_rule_count,
};
}
//
// NOTE: this is *almost* a copy of the JisonParserError producing code in
// jison/lib/jison.js @ line 2304:lrGeneratorMixin.generateErrorClass
//
function generateErrorClass() {
// --- START lexer error class ---
var prelude = `/**
* See also:
* http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/#35881508
* but we keep the prototype.constructor and prototype.name assignment lines too for compatibility
* with userland code which might access the derived class in a 'classic' way.
*
* @public
* @constructor
* @nocollapse
*/
function JisonLexerError(msg, hash) {
Object.defineProperty(this, 'name', {
enumerable: false,
writable: false,
value: 'JisonLexerError'
});
if (msg == null) msg = '???';
Object.defineProperty(this, 'message', {
enumerable: false,
writable: true,
value: msg
});
this.hash = hash;
var stacktrace;
if (hash && hash.exception instanceof Error) {
var ex2 = hash.exception;
this.message = ex2.message || msg;
stacktrace = ex2.stack;
}
if (!stacktrace) {
if (Error.hasOwnProperty('captureStackTrace')) { // V8
Error.captureStackTrace(this, this.constructor);
} else {
stacktrace = (new Error(msg)).stack;
}
}
if (stacktrace) {
Object.defineProperty(this, 'stack', {
enumerable: false,
writable: false,
value: stacktrace
});
}
}
if (typeof Object.setPrototypeOf === 'function') {
Object.setPrototypeOf(JisonLexerError.prototype, Error.prototype);
} else {
JisonLexerError.prototype = Object.create(Error.prototype);