forked from jviereck/regjsparser
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
1654 lines (1481 loc) · 57.9 KB
/
parser.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
// regjsparser
//
// ==================================================================
//
// See ECMA-262 Standard: 15.10.1
//
// NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the
// term "Anchor" is used.
//
// Pattern ::
// Disjunction
//
// Disjunction ::
// Alternative
// Alternative | Disjunction
//
// Alternative ::
// [empty]
// Alternative Term
//
// Term ::
// Anchor
// Anchor Quantifier (see https://github.com/jviereck/regjsparser/issues/130)
// Atom
// Atom Quantifier
//
// Anchor ::
// ^
// $
// \ b
// \ B
// ( ? = Disjunction )
// ( ? ! Disjunction )
// ( ? < = Disjunction )
// ( ? < ! Disjunction )
//
// Quantifier ::
// QuantifierPrefix
// QuantifierPrefix ?
//
// QuantifierPrefix ::
// *
// +
// ?
// { DecimalDigits }
// { DecimalDigits , }
// { DecimalDigits , DecimalDigits }
//
// Atom ::
// PatternCharacter
// .
// \ AtomEscape
// CharacterClass
// ( GroupSpecifier Disjunction )
// ( ? : Disjunction )
//
// PatternCharacter ::
// SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } |
//
// AtomEscape ::
// DecimalEscape
// CharacterClassEscape
// CharacterEscape
// k GroupName
//
// CharacterEscape[U] ::
// ControlEscape
// c ControlLetter
// HexEscapeSequence
// RegExpUnicodeEscapeSequence[?U] (ES6)
// IdentityEscape[?U]
//
// ControlEscape ::
// one of f n r t v
// ControlLetter ::
// one of
// a b c d e f g h i j k l m n o p q r s t u v w x y z
// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
//
// IdentityEscape ::
// SourceCharacter but not c
//
// DecimalEscape ::
// DecimalIntegerLiteral [lookahead ∉ DecimalDigit]
//
// CharacterClassEscape ::
// one of d D s S w W
//
// CharacterClass ::
// [ [lookahead ∉ {^}] ClassRanges ]
// [ ^ ClassRanges ]
//
// ClassRanges ::
// [empty]
// [~V] NonemptyClassRanges
// [+V] ClassContents
//
// NonemptyClassRanges ::
// ClassAtom
// ClassAtom NonemptyClassRangesNoDash
// ClassAtom - ClassAtom ClassRanges
//
// NonemptyClassRangesNoDash ::
// ClassAtom
// ClassAtomNoDash NonemptyClassRangesNoDash
// ClassAtomNoDash - ClassAtom ClassRanges
//
// ClassAtom ::
// -
// ClassAtomNoDash
//
// ClassAtomNoDash ::
// SourceCharacter but not one of \ or ] or -
// \ ClassEscape
//
// ClassEscape ::
// DecimalEscape
// b
// CharacterEscape
// CharacterClassEscape
//
// GroupSpecifier ::
// [empty]
// ? GroupName
//
// GroupName ::
// < RegExpIdentifierName >
//
// RegExpIdentifierName ::
// RegExpIdentifierStart
// RegExpIdentifierName RegExpIdentifierContinue
//
// RegExpIdentifierStart ::
// UnicodeIDStart
// $
// _
// \ RegExpUnicodeEscapeSequence
//
// RegExpIdentifierContinue ::
// UnicodeIDContinue
// $
// _
// \ RegExpUnicodeEscapeSequence
// <ZWNJ>
// <ZWJ>
//
// --------------------------------------------------------------
// NOTE: The following productions refer to the "set notation and
// properties of strings" proposal.
// https://github.com/tc39/proposal-regexp-set-notation
// --------------------------------------------------------------
//
// ClassContents ::
// ClassUnion
// ClassIntersection
// ClassSubtraction
//
// ClassUnion ::
// ClassRange ClassUnion?
// ClassOperand ClassUnion?
//
// ClassIntersection ::
// ClassOperand && [lookahead ≠ &] ClassOperand
// ClassIntersection && [lookahead ≠ &] ClassOperand
//
// ClassSubtraction ::
// ClassOperand -- ClassOperand
// ClassSubtraction -- ClassOperand
//
// ClassOperand ::
// ClassCharacter
// ClassStrings
// NestedClass
//
// NestedClass ::
// [ [lookahead ≠ ^] ClassRanges[+U,+V] ]
// [ ^ ClassRanges[+U,+V] ]
// \ CharacterClassEscape[+U, +V]
//
// ClassRange ::
// ClassCharacter - ClassCharacter
//
// ClassCharacter ::
// [lookahead ∉ ClassReservedDouble] SourceCharacter but not ClassSyntaxCharacter
// \ CharacterEscape[+U]
// \ ClassHalfOfDouble
// \ b
//
// ClassSyntaxCharacter ::
// one of ( ) [ ] { } / - \ |
//
// ClassStrings ::
// ( ClassString MoreClassStrings? )
//
// MoreClassStrings ::
// | ClassString MoreClassStrings?
//
// ClassString ::
// [empty]
// NonEmptyClassString
//
// NonEmptyClassString ::
// ClassCharacter NonEmptyClassString?
//
// ClassReservedDouble ::
// one of && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ __ `` ~~
//
// ClassHalfOfDouble ::
// one of & - ! # % , : ; < = > @ _ ` ~
//
// --------------------------------------------------------------
// NOTE: The following productions refer to the
// "Regular Expression Pattern Modifiers for ECMAScript" proposal.
// https://github.com/tc39/proposal-regexp-modifiers
// --------------------------------------------------------------
//
// Atom ::
// ( ? RegularExpressionFlags : Disjunction )
// ( ? RegularExpressionFlags - RegularExpressionFlags : Disjunction )
//
"use strict";
(function() {
var fromCodePoint = String.fromCodePoint || (function() {
// Implementation taken from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
var stringFromCharCode = String.fromCharCode;
var floor = Math.floor;
return function fromCodePoint() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) != codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint);
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
};
}());
function parse(str, flags, features) {
if (!features) {
features = {};
}
function addRaw(node) {
node.raw = str.substring(node.range[0], node.range[1]);
return node;
}
function updateRawStart(node, start) {
node.range[0] = start;
return addRaw(node);
}
function createAnchor(kind, rawLength) {
return addRaw({
type: 'anchor',
kind: kind,
range: [
pos - rawLength,
pos
]
});
}
function createValue(kind, codePoint, from, to) {
return addRaw({
type: 'value',
kind: kind,
codePoint: codePoint,
range: [from, to]
});
}
function createEscaped(kind, codePoint, value, fromOffset) {
fromOffset = fromOffset || 0;
return createValue(kind, codePoint, pos - (value.length + fromOffset), pos);
}
function createCharacter(matches) {
var _char = matches[0];
var first = _char.charCodeAt(0);
if (isUnicodeMode) {
var second;
if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) {
second = lookahead().charCodeAt(0);
if (second >= 0xDC00 && second <= 0xDFFF) {
// Unicode surrogate pair
pos++;
return createValue(
'symbol',
(first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000,
pos - 2, pos);
}
}
}
return createValue('symbol', first, pos - 1, pos);
}
function createDisjunction(alternatives, from, to) {
return addRaw({
type: 'disjunction',
body: alternatives,
range: [
from,
to
]
});
}
function createDot() {
return addRaw({
type: 'dot',
range: [
pos - 1,
pos
]
});
}
function createCharacterClassEscape(value) {
return addRaw({
type: 'characterClassEscape',
value: value,
range: [
pos - 2,
pos
]
});
}
function createReference(matchIndex) {
return addRaw({
type: 'reference',
matchIndex: parseInt(matchIndex, 10),
range: [
pos - 1 - matchIndex.length,
pos
]
});
}
function createNamedReference(name) {
return addRaw({
type: 'reference',
name: name,
range: [
name.range[0] - 3,
pos
]
});
}
function createGroup(behavior, disjunction, from, to) {
return addRaw({
type: 'group',
behavior: behavior,
body: disjunction,
range: [
from,
to
]
});
}
function createQuantifier(min, max, from, to, symbol) {
if (to == null) {
from = pos - 1;
to = pos;
}
return addRaw({
type: 'quantifier',
min: min,
max: max,
greedy: true,
body: null, // set later on
symbol: symbol,
range: [
from,
to
]
});
}
function createAlternative(terms, from, to) {
return addRaw({
type: 'alternative',
body: terms,
range: [
from,
to
]
});
}
function createCharacterClass(contents, negative, from, to) {
return addRaw({
type: 'characterClass',
kind: contents.kind,
body: contents.body,
negative: negative,
range: [
from,
to
]
});
}
function createClassRange(min, max, from, to) {
// See 15.10.2.15:
if (min.codePoint > max.codePoint) {
bail('invalid range in character class', min.raw + '-' + max.raw, from, to);
}
return addRaw({
type: 'characterClassRange',
min: min,
max: max,
range: [
from,
to
]
});
}
function createClassStrings(strings, from, to) {
return addRaw({
type: 'classStrings',
strings: strings,
range: [from, to]
});
}
function createClassString(characters, from, to) {
return addRaw({
type: 'classString',
characters: characters,
range: [from, to]
});
}
function flattenBody(body) {
if (body.type === 'alternative') {
return body.body;
} else {
return [body];
}
}
function incr(amount) {
amount = (amount || 1);
var res = str.substring(pos, pos + amount);
pos += (amount || 1);
return res;
}
function skip(value) {
if (!match(value)) {
bail('character', value);
}
}
function match(value) {
if (str.indexOf(value, pos) === pos) {
return incr(value.length);
}
}
function lookahead() {
return str[pos];
}
function current(value) {
return str.indexOf(value, pos) === pos;
}
function next(value) {
return str[pos + 1] === value;
}
function matchReg(regExp) {
var subStr = str.substring(pos);
var res = subStr.match(regExp);
if (res) {
res.range = [];
res.range[0] = pos;
incr(res[0].length);
res.range[1] = pos;
}
return res;
}
function parseDisjunction() {
// Disjunction ::
// Alternative
// Alternative | Disjunction
var res = [], from = pos;
res.push(parseAlternative());
while (match('|')) {
res.push(parseAlternative());
}
if (res.length === 1) {
return res[0];
}
return createDisjunction(res, from, pos);
}
function parseAlternative() {
var res = [], from = pos;
var term;
// Alternative ::
// [empty]
// Alternative Term
while (term = parseTerm()) {
res.push(term);
}
if (res.length === 1) {
return res[0];
}
return createAlternative(res, from, pos);
}
function parseTerm() {
// Term ::
// Anchor
// Anchor Quantifier (see https://github.com/jviereck/regjsparser/issues/130)
// Atom
// Atom Quantifier
if (pos >= str.length || current('|') || current(')')) {
return null; /* Means: The term is empty */
}
var anchorOrAtom = parseAnchor();
// If there is no Anchor, try to parse an atom.
if (!anchorOrAtom) {
var atom = parseAtomAndExtendedAtom();
var quantifier;
if (!atom) {
// Check if a quantifier is following. A quantifier without an atom
// is an error.
var pos_backup = pos
quantifier = parseQuantifier() || false;
if (quantifier) {
pos = pos_backup
bail('Expected atom');
}
// If no unicode flag, then try to parse ExtendedAtom -> ExtendedPatternCharacter.
// ExtendedPatternCharacter
var res;
if (!isUnicodeMode && (res = matchReg(/^{/))) {
atom = createCharacter(res);
} else {
bail('Expected atom');
}
}
anchorOrAtom = atom;
}
quantifier = parseQuantifier() || false;
if (quantifier) {
var type = anchorOrAtom.type, behavior = anchorOrAtom.behavior;
if (
type === "group" &&
(behavior === "negativeLookbehind" ||
behavior === "lookbehind" ||
(isUnicodeMode &&
(behavior === "negativeLookahead" || behavior === "lookahead")))
) {
bail(
"Invalid quantifier",
"",
quantifier.range[0],
quantifier.range[1]
);
}
quantifier.body = flattenBody(anchorOrAtom);
// The quantifier contains the atom. Therefore, the beginning of the
// quantifier range is given by the beginning of the atom.
updateRawStart(quantifier, anchorOrAtom.range[0]);
return quantifier;
}
return anchorOrAtom;
}
function parseGroup(matchA, typeA, matchB, typeB) {
var type = null, from = pos;
if (match(matchA)) {
type = typeA;
} else if (match(matchB)) {
type = typeB;
} else {
return false;
}
return finishGroup(type, from);
}
function finishGroup(type, from) {
var body = parseDisjunction();
if (!body) {
bail('Expected disjunction');
}
skip(')');
var group = createGroup(type, flattenBody(body), from, pos);
if (type == 'normal') {
// Keep track of the number of closed groups. This is required for
// parseDecimalEscape(). In case the string is parsed a second time the
// value already holds the total count and no incrementation is required.
if (firstIteration) {
closedCaptureCounter++;
}
}
return group;
}
function parseAnchor() {
// Anchor ::
// ^
// $
// \ b
// \ B
// ( ? = Disjunction )
// ( ? ! Disjunction )
if (match('^')) {
return createAnchor('start', 1 /* rawLength */);
} else if (match('$')) {
return createAnchor('end', 1 /* rawLength */);
} else if (match('\\b')) {
return createAnchor('boundary', 2 /* rawLength */);
} else if (match('\\B')) {
return createAnchor('not-boundary', 2 /* rawLength */);
} else {
return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead');
}
}
function parseQuantifier() {
// Quantifier ::
// QuantifierPrefix
// QuantifierPrefix ?
//
// QuantifierPrefix ::
// *
// +
// ?
// { DecimalDigits }
// { DecimalDigits , }
// { DecimalDigits , DecimalDigits }
var res, from = pos;
var quantifier;
var min, max;
if (match('*')) {
quantifier = createQuantifier(0, undefined, undefined, undefined, '*');
}
else if (match('+')) {
quantifier = createQuantifier(1, undefined, undefined, undefined, "+");
}
else if (match('?')) {
quantifier = createQuantifier(0, 1, undefined, undefined, "?");
}
else if (res = matchReg(/^\{([0-9]+)\}/)) {
min = parseInt(res[1], 10);
quantifier = createQuantifier(min, min, res.range[0], res.range[1]);
}
else if (res = matchReg(/^\{([0-9]+),\}/)) {
min = parseInt(res[1], 10);
quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]);
}
else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) {
min = parseInt(res[1], 10);
max = parseInt(res[2], 10);
if (min > max) {
bail('numbers out of order in {} quantifier', '', from, pos);
}
quantifier = createQuantifier(min, max, res.range[0], res.range[1]);
}
if ((min && !Number.isSafeInteger(min)) || (max && !Number.isSafeInteger(max))) {
bail("iterations outside JS safe integer range in quantifier", "", from, pos);
}
if (quantifier) {
if (match('?')) {
quantifier.greedy = false;
quantifier.range[1] += 1;
}
}
return quantifier;
}
function parseAtomAndExtendedAtom() {
// Parsing Atom and ExtendedAtom together due to redundancy.
// ExtendedAtom is defined in Apendix B of the ECMA-262 standard.
//
// SEE: https://www.ecma-international.org/ecma-262/10.0/index.html#prod-annexB-ExtendedPatternCharacter
//
// Atom ::
// PatternCharacter
// .
// \ AtomEscape
// CharacterClass
// ( GroupSpecifier Disjunction )
// ( ? RegularExpressionFlags : Disjunction )
// ( ? RegularExpressionFlags - RegularExpressionFlags : Disjunction )
// ExtendedAtom ::
// ExtendedPatternCharacter
// ExtendedPatternCharacter ::
// SourceCharacter but not one of ^$\.*+?()[|
var res;
// jviereck: allow ']', '}' here as well to be compatible with browser's
// implementations: ']'.match(/]/);
if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) {
// PatternCharacter
return createCharacter(res);
}
else if (!isUnicodeMode && (res = matchReg(/^(?:]|})/))) {
// ExtendedPatternCharacter, first part. See parseTerm.
return createCharacter(res);
}
else if (match('.')) {
// .
return createDot();
}
else if (match('\\')) {
// \ AtomEscape
res = parseAtomEscape();
if (!res) {
if (!isUnicodeMode && lookahead() == 'c') {
// B.1.4 ExtendedAtom
// \[lookahead = c]
return createValue('symbol', 92, pos - 1, pos);
}
bail('atomEscape');
}
return res;
}
else if (res = parseCharacterClass()) {
return res;
}
else if (features.lookbehind && (res = parseGroup('(?<=', 'lookbehind', '(?<!', 'negativeLookbehind'))) {
return res;
}
else if (features.namedGroups && match("(?<")) {
var name = parseIdentifier();
skip(">");
var group = finishGroup("normal", name.range[0] - 3);
group.name = name;
return group;
}
else if (features.modifiers && str.indexOf("(?") == pos && str[pos + 2] != ":") {
return parseModifiersGroup();
}
else {
// ( Disjunction )
// ( ? : Disjunction )
return parseGroup('(?:', 'ignore', '(', 'normal');
}
}
function parseModifiersGroup() {
function hasDupChar(str) {
var i = 0;
while (i < str.length) {
if (str.indexOf(str[i], i + 1) != -1) {
return true;
}
i++;
}
return false;
}
var from = pos;
incr(2);
var enablingFlags = matchReg(/^[sim]+/);
var disablingFlags;
if(match("-")){
disablingFlags = matchReg(/^[sim]+/);
if (!disablingFlags) {
bail('Invalid flags for modifiers group');
}
} else if(!enablingFlags){
bail('Invalid flags for modifiers group');
}
enablingFlags = enablingFlags ? enablingFlags[0] : "";
disablingFlags = disablingFlags ? disablingFlags[0] : "";
var flags = enablingFlags + disablingFlags;
if(flags.length > 3 || hasDupChar(flags)) {
bail('flags cannot be duplicated for modifiers group');
}
skip(":");
var modifiersGroup = finishGroup("ignore", from);
modifiersGroup.modifierFlags = {
enabling: enablingFlags,
disabling: disablingFlags
};
return modifiersGroup;
}
function parseUnicodeSurrogatePairEscape(firstEscape) {
if (isUnicodeMode) {
var first, second;
if (firstEscape.kind == 'unicodeEscape' &&
(first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF &&
current('\\') && next('u') ) {
var prevPos = pos;
pos++;
var secondEscape = parseClassEscape();
if (secondEscape.kind == 'unicodeEscape' &&
(second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) {
// Unicode surrogate pair
firstEscape.range[1] = secondEscape.range[1];
firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
firstEscape.type = 'value';
firstEscape.kind = 'unicodeCodePointEscape';
addRaw(firstEscape);
}
else {
pos = prevPos;
}
}
}
return firstEscape;
}
function parseClassEscape() {
return parseAtomEscape(true);
}
function parseAtomEscape(insideCharacterClass) {
// AtomEscape ::
// DecimalEscape
// CharacterEscape
// CharacterClassEscape
// k GroupName
var res, from = pos;
res = parseDecimalEscape(insideCharacterClass) || parseNamedReference();
if (res) {
return res;
}
// For ClassEscape
if (insideCharacterClass) {
// b
if (match('b')) {
// 15.10.2.19
// The production ClassEscape :: b evaluates by returning the
// CharSet containing the one character <BS> (Unicode value 0008).
return createEscaped('singleEscape', 0x0008, '\\b');
} else if (match('B')) {
bail('\\B not possible inside of CharacterClass', '', from);
} else if (!isUnicodeMode && (res = matchReg(/^c([0-9])/))) {
// B.1.4
// c ClassControlLetter, ClassControlLetter = DecimalDigit
return createEscaped('controlLetter', res[1] + 16, res[1], 2);
} else if (!isUnicodeMode && (res = matchReg(/^c_/))) {
// B.1.4
// c ClassControlLetter, ClassControlLetter = _
return createEscaped('controlLetter', 31, '_', 2);
}
// [+U] -
if (isUnicodeMode && match('-')) {
return createEscaped('singleEscape', 0x002d, '\\-');
}
}
res = parseCharacterClassEscape() || parseCharacterEscape();
return res;
}
function parseDecimalEscape(insideCharacterClass) {
// DecimalEscape ::
// DecimalIntegerLiteral [lookahead ∉ DecimalDigit]
var res, match, from = pos;
if (res = matchReg(/^(?!0)\d+/)) {
match = res[0];
var refIdx = parseInt(res[0], 10);
if (refIdx <= closedCaptureCounter && !insideCharacterClass) {
// If the number is smaller than the normal-groups found so
// far, then it is a reference...
return createReference(res[0]);
} else {
// ... otherwise it needs to be interpreted as a octal (if the
// number is in an octal format). If it is NOT octal format,
// then the slash is ignored and the number is matched later
// as normal characters.
// Recall the negative decision to decide if the input must be parsed
// a second time with the total normal-groups.
backrefDenied.push(refIdx);
// \1 octal escapes are disallowed in unicode mode, but they might
// be references to groups which haven't been parsed yet.
// We must parse a second time to determine if \1 is a reference
// or an octal scape, and then we can report the error.
if (firstIteration) {
shouldReparse = true;
} else {
bailOctalEscapeIfUnicode(from, pos);
}
// Reset the position again, as maybe only parts of the previous
// matched numbers are actual octal numbers. E.g. in '019' only
// the '01' should be matched.
incr(-res[0].length);
if (res = matchReg(/^[0-7]{1,3}/)) {
return createEscaped('octal', parseInt(res[0], 8), res[0], 1);
} else {
// If we end up here, we have a case like /\91/. Then the
// first slash is to be ignored and the 9 & 1 to be treated
// like ordinary characters. Create a character for the
// first number only here - other number-characters
// (if available) will be matched later.
res = createCharacter(matchReg(/^[89]/));
return updateRawStart(res, res.range[0] - 1);
}
}
}
// Only allow octal numbers in the following. All matched numbers start
// with a zero (if the do not, the previous if-branch is executed).
// If the number is not octal format and starts with zero (e.g. `091`)
// then only the zeros `0` is treated here and the `91` are ordinary
// characters.
// Example:
// /\091/.exec('\091')[0].length === 3
else if (res = matchReg(/^[0-7]{1,3}/)) {
match = res[0];
if (match !== '0') {
bailOctalEscapeIfUnicode(from, pos);
}
if (/^0{1,3}$/.test(match)) {
// If they are all zeros, then only take the first one.
return createEscaped('null', 0x0000, '0', match.length);
} else {
return createEscaped('octal', parseInt(match, 8), match, 1);
}
}
return false;
}