forked from eslint-community/regexpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.ts
878 lines (801 loc) · 23.6 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
import type {
Alternative,
Backreference,
CapturingGroup,
CharacterClass,
CharacterClassElement,
CharacterClassRange,
Flags,
Group,
RegExpLiteral,
LookaroundAssertion,
Pattern,
Quantifier,
ClassStringDisjunction,
ClassIntersection,
ClassSubtraction,
UnicodeSetsCharacterClassElement,
ClassSetOperand,
UnicodePropertyCharacterSet,
UnicodeSetsCharacterClass,
ExpressionCharacterClass,
StringAlternative,
} 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
| 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 _expressionBuffer: ClassIntersection | ClassSubtraction | null =
null
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 group =
typeof ref === "number"
? this._capturingGroups[ref - 1]
: this._capturingGroups.find((g) => g.name === ref)!
reference.resolved = group
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")
}
this._node = {
type: "Group",
parent,
start,
end: start,
raw: "",
alternatives: [],
}
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 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 as CharacterClassElement[]).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") ||
(strings && (negate || value))
) {
throw new Error("UnknownError")
}
const base = {
type: "CharacterSet",
parent,
start,
end,
raw: this.source.slice(start, end),
kind,
strings,
key,
} as const
const node: UnicodePropertyCharacterSet = strings
? {
...base,
value: null,
negate: false,
strings: true,
}
: {
...base,
value,
negate,
strings: false,
}
parent.elements.push(node)
}
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,
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") ||
(this._expressionBuffer && node.elements.length > 0)
) {
throw new Error("UnknownError")
}
const parent = node.parent
node.end = end
node.raw = this.source.slice(start, end)
this._node = parent
const expression = this._expressionBuffer
this._expressionBuffer = null
if (!expression) {
return
}
// 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._expressionBuffer ?? 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._expressionBuffer = 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._expressionBuffer ?? 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._expressionBuffer = 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 `2024`.
* - `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.
*/
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
}
}