forked from mysticatea/regexpp
-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
parser.ts
973 lines (887 loc) · 26.1 KB
/
parser.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
import type {
Alternative,
Backreference,
CapturingGroup,
CharacterClass,
CharacterClassRange,
Flags,
Group,
RegExpLiteral,
LookaroundAssertion,
Pattern,
Quantifier,
ClassStringDisjunction,
ClassIntersection,
ClassSubtraction,
UnicodeSetsCharacterClassElement,
ClassSetOperand,
UnicodeSetsCharacterClass,
ExpressionCharacterClass,
StringAlternative,
Modifiers,
} from "./ast"
import type { EcmaVersion } from "./ecma-versions"
import { latestEcmaVersion } from "./ecma-versions"
import { HYPHEN_MINUS } from "./unicode"
import { RegExpValidator } from "./validator"
type AppendableNode =
| Alternative
| CapturingGroup
| CharacterClass
| ClassStringDisjunction
| Group
| LookaroundAssertion
| Modifiers
| Pattern
| StringAlternative
const DUMMY_PATTERN: Pattern = {} as Pattern
const DUMMY_FLAGS: Flags = {} as Flags
const DUMMY_CAPTURING_GROUP: CapturingGroup = {} as CapturingGroup
function isClassSetOperand(
node: UnicodeSetsCharacterClassElement,
): node is ClassSetOperand {
return (
node.type === "Character" ||
node.type === "CharacterSet" ||
node.type === "CharacterClass" ||
node.type === "ExpressionCharacterClass" ||
node.type === "ClassStringDisjunction"
)
}
class RegExpParserState {
public readonly strict: boolean
public readonly ecmaVersion: EcmaVersion
private _node: AppendableNode = DUMMY_PATTERN
private _expressionBufferMap = new Map<
CharacterClass | ExpressionCharacterClass,
ClassIntersection | ClassSubtraction
>()
private _flags: Flags = DUMMY_FLAGS
private _backreferences: Backreference[] = []
private _capturingGroups: CapturingGroup[] = []
public source = ""
public constructor(options?: RegExpParser.Options) {
this.strict = Boolean(options?.strict)
this.ecmaVersion = options?.ecmaVersion ?? latestEcmaVersion
}
public get pattern(): Pattern {
if (this._node.type !== "Pattern") {
throw new Error("UnknownError")
}
return this._node
}
public get flags(): Flags {
if (this._flags.type !== "Flags") {
throw new Error("UnknownError")
}
return this._flags
}
public onRegExpFlags(
start: number,
end: number,
{
global,
ignoreCase,
multiline,
unicode,
sticky,
dotAll,
hasIndices,
unicodeSets,
}: {
global: boolean
ignoreCase: boolean
multiline: boolean
unicode: boolean
sticky: boolean
dotAll: boolean
hasIndices: boolean
unicodeSets: boolean
},
): void {
this._flags = {
type: "Flags",
parent: null,
start,
end,
raw: this.source.slice(start, end),
global,
ignoreCase,
multiline,
unicode,
sticky,
dotAll,
hasIndices,
unicodeSets,
}
}
public onPatternEnter(start: number): void {
this._node = {
type: "Pattern",
parent: null,
start,
end: start,
raw: "",
alternatives: [],
}
this._backreferences.length = 0
this._capturingGroups.length = 0
}
public onPatternLeave(start: number, end: number): void {
this._node.end = end
this._node.raw = this.source.slice(start, end)
for (const reference of this._backreferences) {
const ref = reference.ref
const groups =
typeof ref === "number"
? [this._capturingGroups[ref - 1]]
: this._capturingGroups.filter((g) => g.name === ref)
if (groups.length === 1) {
const group = groups[0]
reference.ambiguous = false
reference.resolved = group
} else {
reference.ambiguous = true
reference.resolved = groups
}
for (const group of groups) {
group.references.push(reference)
}
}
}
public onAlternativeEnter(start: number): void {
const parent = this._node
if (
parent.type !== "Assertion" &&
parent.type !== "CapturingGroup" &&
parent.type !== "Group" &&
parent.type !== "Pattern"
) {
throw new Error("UnknownError")
}
this._node = {
type: "Alternative",
parent,
start,
end: start,
raw: "",
elements: [],
}
parent.alternatives.push(this._node)
}
public onAlternativeLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onGroupEnter(start: number): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
const group: Group = {
type: "Group",
parent,
start,
end: start,
raw: "",
modifiers: null,
alternatives: [],
}
this._node = group
parent.elements.push(this._node)
}
public onGroupLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Group" || node.parent.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onModifiersEnter(start: number): void {
const parent = this._node
if (parent.type !== "Group") {
throw new Error("UnknownError")
}
this._node = {
type: "Modifiers",
parent,
start,
end: start,
raw: "",
add: null as never, // Set in onAddModifiers.
remove: null,
}
parent.modifiers = this._node
}
public onModifiersLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Modifiers" || node.parent.type !== "Group") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onAddModifiers(
start: number,
end: number,
{
ignoreCase,
multiline,
dotAll,
}: { ignoreCase: boolean; multiline: boolean; dotAll: boolean },
): void {
const parent = this._node
if (parent.type !== "Modifiers") {
throw new Error("UnknownError")
}
parent.add = {
type: "ModifierFlags",
parent,
start,
end,
raw: this.source.slice(start, end),
ignoreCase,
multiline,
dotAll,
}
}
public onRemoveModifiers(
start: number,
end: number,
{
ignoreCase,
multiline,
dotAll,
}: { ignoreCase: boolean; multiline: boolean; dotAll: boolean },
): void {
const parent = this._node
if (parent.type !== "Modifiers") {
throw new Error("UnknownError")
}
parent.remove = {
type: "ModifierFlags",
parent,
start,
end,
raw: this.source.slice(start, end),
ignoreCase,
multiline,
dotAll,
}
}
public onCapturingGroupEnter(start: number, name: string | null): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
this._node = {
type: "CapturingGroup",
parent,
start,
end: start,
raw: "",
name,
alternatives: [],
references: [],
}
parent.elements.push(this._node)
this._capturingGroups.push(this._node)
}
public onCapturingGroupLeave(start: number, end: number): void {
const node = this._node
if (
node.type !== "CapturingGroup" ||
node.parent.type !== "Alternative"
) {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onQuantifier(
start: number,
end: number,
min: number,
max: number,
greedy: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
// Replace the last element.
const element = parent.elements.pop()
if (
element == null ||
element.type === "Quantifier" ||
(element.type === "Assertion" && element.kind !== "lookahead")
) {
throw new Error("UnknownError")
}
const node: Quantifier = {
type: "Quantifier",
parent,
start: element.start,
end,
raw: this.source.slice(element.start, end),
min,
max,
greedy,
element,
}
parent.elements.push(node)
element.parent = node
}
public onLookaroundAssertionEnter(
start: number,
kind: "lookahead" | "lookbehind",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
const node: LookaroundAssertion = (this._node = {
type: "Assertion",
parent,
start,
end: start,
raw: "",
kind,
negate,
alternatives: [],
})
parent.elements.push(node)
}
public onLookaroundAssertionLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "Assertion" || node.parent.type !== "Alternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onEdgeAssertion(
start: number,
end: number,
kind: "end" | "start",
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "Assertion",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
})
}
public onWordBoundaryAssertion(
start: number,
end: number,
kind: "word",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "Assertion",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
negate,
})
}
public onAnyCharacterSet(start: number, end: number, kind: "any"): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
})
}
public onEscapeCharacterSet(
start: number,
end: number,
kind: "digit" | "space" | "word",
negate: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
parent.elements.push({
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
negate,
})
}
public onUnicodePropertyCharacterSet(
start: number,
end: number,
kind: "property",
key: string,
value: string | null,
negate: boolean,
strings: boolean,
): void {
const parent = this._node
if (parent.type !== "Alternative" && parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
const base = {
type: "CharacterSet",
parent: null,
start,
end,
raw: this.source.slice(start, end),
kind,
strings: null,
key,
} as const
if (strings) {
if (
(parent.type === "CharacterClass" && !parent.unicodeSets) ||
negate ||
value !== null
) {
throw new Error("UnknownError")
}
parent.elements.push({ ...base, parent, strings, value, negate })
} else {
parent.elements.push({ ...base, parent, strings, value, negate })
}
}
public onCharacter(start: number, end: number, value: number): void {
const parent = this._node
if (
parent.type !== "Alternative" &&
parent.type !== "CharacterClass" &&
parent.type !== "StringAlternative"
) {
throw new Error("UnknownError")
}
parent.elements.push({
type: "Character",
parent,
start,
end,
raw: this.source.slice(start, end),
value,
})
}
public onBackreference(
start: number,
end: number,
ref: number | string,
): void {
const parent = this._node
if (parent.type !== "Alternative") {
throw new Error("UnknownError")
}
const node: Backreference = {
type: "Backreference",
parent,
start,
end,
raw: this.source.slice(start, end),
ref,
ambiguous: false,
resolved: DUMMY_CAPTURING_GROUP,
}
parent.elements.push(node)
this._backreferences.push(node)
}
public onCharacterClassEnter(
start: number,
negate: boolean,
unicodeSets: boolean,
): void {
const parent = this._node
const base = {
type: "CharacterClass" as const,
parent,
start,
end: start,
raw: "",
unicodeSets,
negate,
elements: [],
}
if (parent.type === "Alternative") {
const node: CharacterClass = {
...base,
parent,
}
this._node = node
parent.elements.push(node)
} else if (
parent.type === "CharacterClass" &&
parent.unicodeSets &&
unicodeSets
) {
const node: UnicodeSetsCharacterClass = {
...base,
parent,
unicodeSets,
}
this._node = node
parent.elements.push(node)
} else {
throw new Error("UnknownError")
}
}
public onCharacterClassLeave(start: number, end: number): void {
const node = this._node
if (
node.type !== "CharacterClass" ||
(node.parent.type !== "Alternative" &&
node.parent.type !== "CharacterClass")
) {
throw new Error("UnknownError")
}
const parent = node.parent
node.end = end
node.raw = this.source.slice(start, end)
this._node = parent
const expression = this._expressionBufferMap.get(node)
if (!expression) {
return
}
if (node.elements.length > 0) {
throw new Error("UnknownError")
}
this._expressionBufferMap.delete(node)
// Replace with ExpressionCharacterClass.
const newNode: ExpressionCharacterClass = {
type: "ExpressionCharacterClass",
parent,
start: node.start,
end: node.end,
raw: node.raw,
negate: node.negate,
expression,
}
expression.parent = newNode
if (node !== parent.elements.pop()) {
throw new Error("UnknownError")
}
parent.elements.push(newNode)
}
public onCharacterClassRange(start: number, end: number): void {
const parent = this._node
if (parent.type !== "CharacterClass") {
throw new Error("UnknownError")
}
// Replace the last three elements.
const elements = parent.elements
const max = elements.pop()
if (!max || max.type !== "Character") {
throw new Error("UnknownError")
}
if (!parent.unicodeSets) {
const hyphen = elements.pop()
if (
!hyphen ||
hyphen.type !== "Character" ||
hyphen.value !== HYPHEN_MINUS
) {
throw new Error("UnknownError")
}
}
const min = elements.pop()
if (!min || min.type !== "Character") {
throw new Error("UnknownError")
}
const node: CharacterClassRange = {
type: "CharacterClassRange",
parent,
start,
end,
raw: this.source.slice(start, end),
min,
max,
}
min.parent = node
max.parent = node
elements.push(node)
}
public onClassIntersection(start: number, end: number): void {
const parent = this._node
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
throw new Error("UnknownError")
}
// Replace the last two elements.
const right = parent.elements.pop()
const left =
this._expressionBufferMap.get(parent) ?? parent.elements.pop()
if (
!left ||
!right ||
left.type === "ClassSubtraction" ||
(left.type !== "ClassIntersection" && !isClassSetOperand(left)) ||
!isClassSetOperand(right)
) {
throw new Error("UnknownError")
}
const node: ClassIntersection = {
type: "ClassIntersection",
parent:
// Temporarily cast. We will actually replace it later in `onCharacterClassLeave`.
parent as never as ExpressionCharacterClass,
start,
end,
raw: this.source.slice(start, end),
left,
right,
}
left.parent = node
right.parent = node
this._expressionBufferMap.set(parent, node)
}
public onClassSubtraction(start: number, end: number): void {
const parent = this._node
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
throw new Error("UnknownError")
}
// Replace the last two elements.
const right = parent.elements.pop()
const left =
this._expressionBufferMap.get(parent) ?? parent.elements.pop()
if (
!left ||
!right ||
left.type === "ClassIntersection" ||
(left.type !== "ClassSubtraction" && !isClassSetOperand(left)) ||
!isClassSetOperand(right)
) {
throw new Error("UnknownError")
}
const node: ClassSubtraction = {
type: "ClassSubtraction",
parent:
// Temporarily cast. We will actually replace it later in `onCharacterClassLeave`.
parent as never as ExpressionCharacterClass,
start,
end,
raw: this.source.slice(start, end),
left,
right,
}
left.parent = node
right.parent = node
this._expressionBufferMap.set(parent, node)
}
public onClassStringDisjunctionEnter(start: number): void {
const parent = this._node
if (parent.type !== "CharacterClass" || !parent.unicodeSets) {
throw new Error("UnknownError")
}
this._node = {
type: "ClassStringDisjunction",
parent,
start,
end: start,
raw: "",
alternatives: [],
}
parent.elements.push(this._node)
}
public onClassStringDisjunctionLeave(start: number, end: number): void {
const node = this._node
if (
node.type !== "ClassStringDisjunction" ||
node.parent.type !== "CharacterClass"
) {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
public onStringAlternativeEnter(start: number): void {
const parent = this._node
if (parent.type !== "ClassStringDisjunction") {
throw new Error("UnknownError")
}
this._node = {
type: "StringAlternative",
parent,
start,
end: start,
raw: "",
elements: [],
}
parent.alternatives.push(this._node)
}
public onStringAlternativeLeave(start: number, end: number): void {
const node = this._node
if (node.type !== "StringAlternative") {
throw new Error("UnknownError")
}
node.end = end
node.raw = this.source.slice(start, end)
this._node = node.parent
}
}
export namespace RegExpParser {
/**
* The options for RegExpParser construction.
*/
export interface Options {
/**
* The flag to disable Annex B syntax. Default is `false`.
*/
strict?: boolean
/**
* ECMAScript version. Default is `2025`.
* - `2015` added `u` and `y` flags.
* - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion,
* and Unicode Property Escape.
* - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes.
* - `2022` added `d` flag.
* - `2023` added more valid Unicode Property Escapes.
* - `2024` added `v` flag.
* - `2025` added duplicate named capturing groups, modifiers.
*/
ecmaVersion?: EcmaVersion
}
}
export class RegExpParser {
private _state: RegExpParserState
private _validator: RegExpValidator
/**
* Initialize this parser.
* @param options The options of parser.
*/
public constructor(options?: RegExpParser.Options) {
this._state = new RegExpParserState(options)
this._validator = new RegExpValidator(this._state)
}
/**
* Parse a regular expression literal. E.g. "/abc/g"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @returns The AST of the given regular expression.
*/
public parseLiteral(
source: string,
start = 0,
end: number = source.length,
): RegExpLiteral {
this._state.source = source
this._validator.validateLiteral(source, start, end)
const pattern = this._state.pattern
const flags = this._state.flags
const literal: RegExpLiteral = {
type: "RegExpLiteral",
parent: null,
start,
end,
raw: source,
pattern,
flags,
}
pattern.parent = literal
flags.parent = literal
return literal
}
/**
* Parse a regular expression flags. E.g. "gim"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @returns The AST of the given flags.
*/
public parseFlags(
source: string,
start = 0,
end: number = source.length,
): Flags {
this._state.source = source
this._validator.validateFlags(source, start, end)
return this._state.flags
}
/**
* Parse a regular expression pattern. E.g. "abc"
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @param flags The flags.
* @returns The AST of the given pattern.
*/
public parsePattern(
source: string,
start?: number,
end?: number,
flags?: {
unicode?: boolean
unicodeSets?: boolean
},
): Pattern
/**
* @deprecated Backward compatibility
* Use object `flags` instead of boolean `uFlag`.
*
* @param source The source code to parse.
* @param start The start index in the source code.
* @param end The end index in the source code.
* @param uFlag The flag to set unicode mode.
* @returns The AST of the given pattern.
*/
public parsePattern(
source: string,
start?: number,
end?: number,
uFlag?: boolean, // The unicode flag (backward compatibility).
): Pattern
public parsePattern(
source: string,
start = 0,
end: number = source.length,
uFlagOrFlags:
| boolean
| {
unicode?: boolean
unicodeSets?: boolean
}
| undefined = undefined,
): Pattern {
this._state.source = source
this._validator.validatePattern(
source,
start,
end,
uFlagOrFlags as never,
)
return this._state.pattern
}
}