-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasic.ts
1336 lines (1227 loc) · 40.9 KB
/
basic.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { visitRegExpAST } from "@eslint-community/regexpp";
import {
Node,
Group,
CapturingGroup,
Element,
Alternative,
LookaroundAssertion,
Quantifier,
Pattern,
CharacterClassElement,
CharacterClass,
CharacterClassRange,
Character,
RegExpLiteral,
Flags,
Backreference,
CharacterSet,
EdgeAssertion,
WordBoundaryAssertion,
ClassIntersection,
ClassSubtraction,
StringAlternative,
ExpressionCharacterClass,
UnicodeSetsCharacterClass,
ClassStringDisjunction,
ClassRangesCharacterClass,
ClassRangesCharacterClassElement,
UnicodeSetsCharacterClassElement,
ClassSetOperand,
} from "@eslint-community/regexpp/ast";
import { assertNever, isReadonlyArray } from "./util";
import { ReadonlyFlags } from "./flags";
import { toUnicodeSet } from "./to-char-set";
import { JS } from "refa";
export type CharacterElement =
| CharacterSet
| ClassIntersection
| ClassSubtraction
| CharacterClassElement
| CharacterClass
| StringAlternative;
function characterIsEmpty(element: CharacterElement, flags: ReadonlyFlags): boolean {
switch (element.type) {
case "Character":
case "CharacterSet":
case "CharacterClassRange":
return false;
case "CharacterClass":
return (
element.unicodeSets &&
!element.negate &&
element.elements.length > 0 &&
element.elements.every(e => characterIsEmpty(e, flags))
);
case "ExpressionCharacterClass":
return !element.negate && characterIsEmpty(element.expression, flags);
case "ClassIntersection":
case "ClassSubtraction": {
// we actually need to evaluate the operation to implement this correctly
const lengthRange = toUnicodeSet(element, flags).getLengthRange();
return lengthRange !== undefined && lengthRange.min === 0 && lengthRange.max === 0;
}
case "ClassStringDisjunction":
return element.alternatives.every(e => characterIsEmpty(e, flags));
case "StringAlternative":
return element.elements.length === 0;
default:
throw assertNever(element);
}
}
function characterIsPotentiallyEmpty(element: CharacterElement): boolean {
switch (element.type) {
case "Character":
case "CharacterSet":
case "CharacterClassRange":
return false;
case "CharacterClass":
return element.unicodeSets && !element.negate && element.elements.some(characterIsPotentiallyEmpty);
case "ExpressionCharacterClass":
return !element.negate && characterIsPotentiallyEmpty(element.expression);
case "ClassIntersection":
return characterIsPotentiallyEmpty(element.left) && characterIsPotentiallyEmpty(element.right);
case "ClassSubtraction":
return characterIsPotentiallyEmpty(element.left) && !characterIsPotentiallyEmpty(element.right);
case "ClassStringDisjunction":
return element.alternatives.some(characterIsPotentiallyEmpty);
case "StringAlternative":
return element.elements.length === 0;
default:
throw assertNever(element);
}
}
function isInvokeEvery<T>(element: T | readonly T[], fn: (e: T) => boolean): boolean {
if (isReadonlyArray(element)) {
return element.every(fn);
} else {
return fn(element);
}
}
function isInvokeSome<T>(element: T | readonly T[], fn: (e: T) => boolean): boolean {
if (isReadonlyArray(element)) {
return element.some(fn);
} else {
return fn(element);
}
}
/**
* Returns whether all (but at least one of the) paths of the given element do not consume characters.
*
* If this function returns `true`, then {@link isPotentiallyZeroLength} is guaranteed to return `true`.
*
* ## Backreferences
*
* This function uses the same condition for backreferences as {@link isEmpty}.
*
* ## Relations
*
* - `isZeroLength(e) -> isPotentiallyZeroLength(e)`
* - `isZeroLength(e) -> getLengthRange(e).max == 0`
*
* @see {@link isPotentiallyZeroLength}
* @see {@link isEmpty}
* @see {@link isPotentiallyEmpty}
* @see {@link getLengthRange}
*/
export function isZeroLength(
element: Element | CharacterElement | Alternative | readonly Alternative[],
flags: ReadonlyFlags
): boolean {
return isInvokeEvery(element, e => isZeroLengthImpl(e, flags));
}
function isZeroLengthImpl(element: Element | CharacterElement | Alternative, flags: ReadonlyFlags): boolean {
switch (element.type) {
case "Alternative":
return element.elements.every(e => isZeroLengthImpl(e, flags));
case "Assertion":
return true;
case "Character":
case "CharacterSet":
case "CharacterClassRange":
case "CharacterClass":
case "ExpressionCharacterClass":
case "ClassIntersection":
case "ClassSubtraction":
case "ClassStringDisjunction":
case "StringAlternative":
return characterIsEmpty(element, flags);
case "Quantifier":
return element.max === 0 || isZeroLengthImpl(element.element, flags);
case "Backreference":
return isEmptyBackreference(element, flags);
case "CapturingGroup":
case "Group":
return element.alternatives.length > 0 && element.alternatives.every(e => isZeroLengthImpl(e, flags));
default:
throw assertNever(element);
}
}
/**
* Returns whether at least one path of the given element does not consume characters.
*
* ## Backreferences
*
* This function uses the same condition for backreferences as {@link isPotentiallyEmpty}.
*
* ## Relations
*
* - `isPotentiallyZeroLength(e) -> getLengthRange(e).min == 0`
*
* @see {@link isZeroLength}
* @see {@link isEmpty}
* @see {@link isPotentiallyEmpty}
* @see {@link getLengthRange}
*/
export function isPotentiallyZeroLength(
element: Element | CharacterElement | Alternative | readonly Alternative[],
flags: ReadonlyFlags
): boolean {
if (!isReadonlyArray(element)) {
switch (element.type) {
case "Character":
case "CharacterSet":
case "CharacterClassRange":
case "CharacterClass":
case "ExpressionCharacterClass":
case "ClassIntersection":
case "ClassSubtraction":
case "ClassStringDisjunction":
case "StringAlternative":
return characterIsPotentiallyEmpty(element);
}
}
return isInvokeSome(element, e => isPotentiallyZeroLengthImpl(e, e, flags));
}
function isPotentiallyZeroLengthImpl(
e: Element | Alternative,
root: Element | Alternative,
flags: ReadonlyFlags
): boolean {
return impl(e);
function impl(element: Element | Alternative): boolean {
switch (element.type) {
case "Alternative":
return element.elements.every(impl);
case "Assertion":
return true;
case "Backreference":
return backreferenceIsPotentiallyEmpty(element, root, flags);
case "Character":
case "CharacterSet":
case "CharacterClass":
case "ExpressionCharacterClass":
return characterIsPotentiallyEmpty(element);
case "CapturingGroup":
case "Group":
return element.alternatives.some(impl);
case "Quantifier":
return element.min === 0 || impl(element.element);
default:
throw assertNever(element);
}
}
}
/**
* Returns whether all (but at least one of the) paths of the given element do neither consume characters nor assert
* characters.
*
* If this function returns `true`, then {@link isZeroLength} and {@link isPotentiallyEmpty} are guaranteed to return
* `true`.
*
* ## Backreferences
*
* A backreferences will only be considered potentially empty, iff it is empty by the definition of
* {@link isEmptyBackreference}.
*
* ## Relations
*
* - `isEmpty(e) -> isZeroLength(e)`
* - `isEmpty(e) -> isPotentiallyEmpty(e)`
*
* @see {@link isZeroLength}
* @see {@link isPotentiallyZeroLength}
* @see {@link isPotentiallyEmpty}
* @see {@link getLengthRange}
*/
export function isEmpty(
element: Element | CharacterElement | Alternative | readonly Alternative[],
flags: ReadonlyFlags
): boolean {
return isInvokeEvery(element, e => isEmptyImpl(e, flags));
}
function isEmptyImpl(element: Element | CharacterElement | Alternative, flags: ReadonlyFlags): boolean {
switch (element.type) {
case "Alternative":
return element.elements.every(e => isEmptyImpl(e, flags));
case "Assertion":
return false;
case "Backreference":
return isEmptyBackreference(element, flags);
case "Character":
case "CharacterSet":
case "CharacterClassRange":
case "CharacterClass":
case "ExpressionCharacterClass":
case "ClassIntersection":
case "ClassSubtraction":
case "ClassStringDisjunction":
case "StringAlternative":
return characterIsEmpty(element, flags);
case "CapturingGroup":
case "Group":
return element.alternatives.length > 0 && element.alternatives.every(e => isEmptyImpl(e, flags));
case "Quantifier":
return element.max === 0 || isEmptyImpl(element.element, flags);
default:
throw assertNever(element);
}
}
/**
* Returns whether at least one path of the given element does neither consume characters nor assert characters.
*
* ## Backreferences
*
* A backreferences will only be considered potentially empty, iff at least one of the following conditions is true:
*
* - The backreference is trivially always empty. (see {@link isEmptyBackreference})
* - The referenced capturing group is a descendant of the given element and at least one of the following conditions is
* true:
* * The referenced capturing group is potentially zero-length.
* * The backreferences is not always after its referenced capturing group.
* (see {@link isStrictBackreference})
*
* ## Relations
*
* - `isPotentiallyEmpty(e) -> isPotentiallyZeroLength(e)`
*
* @see {@link isZeroLength}
* @see {@link isPotentiallyZeroLength}
* @see {@link isEmpty}
* @see {@link getLengthRange}
*/
export function isPotentiallyEmpty(
element: Element | CharacterElement | Alternative | readonly Alternative[],
flags: ReadonlyFlags
): boolean {
if (!isReadonlyArray(element)) {
switch (element.type) {
case "Character":
case "CharacterSet":
case "CharacterClassRange":
case "CharacterClass":
case "ExpressionCharacterClass":
case "ClassIntersection":
case "ClassSubtraction":
case "ClassStringDisjunction":
case "StringAlternative":
return characterIsPotentiallyEmpty(element);
}
}
return isInvokeSome(element, e => isPotentiallyEmptyImpl(e, flags));
}
function isPotentiallyEmptyImpl(root: Element | Alternative, flags: ReadonlyFlags): boolean {
return impl(root);
function impl(element: Element | Alternative): boolean {
switch (element.type) {
case "Alternative":
return element.elements.every(impl);
case "Assertion":
return false;
case "Backreference":
return backreferenceIsPotentiallyEmpty(element, root, flags);
case "Character":
case "CharacterSet":
case "CharacterClass":
case "ExpressionCharacterClass":
return characterIsPotentiallyEmpty(element);
case "CapturingGroup":
case "Group":
return element.alternatives.some(impl);
case "Quantifier":
return element.min === 0 || impl(element.element);
default:
throw assertNever(element);
}
}
}
function backreferenceIsPotentiallyEmpty(
back: Backreference,
root: Element | Alternative,
flags: ReadonlyFlags
): boolean {
if (isEmptyBackreference(back, flags)) {
return true;
}
const groups = getReferencedGroupsFromBackreference(back);
if (groups.length === 0) return true;
for (const group of groups.filter(group => hasSomeAncestor(group, a => a === root))) {
if (!isStrictBackreference(back) || isPotentiallyZeroLengthImpl(group, root, flags)) {
return true;
}
}
return false;
}
/**
* Returns the type of all possible ancestor nodes of the given node type.
*
* @see {@link hasSomeAncestor}
*/
export type Ancestor<T extends Node> = AncestorImpl<T>;
type AncestorImpl<T extends Node> = ExtendApproximation<Anc2<GetParent<T>>>;
type ExtendApproximation<T extends Node> =
| T
| (T extends UnicodeSetsCharacterClass ? CharacterClassAnc : never)
| (T extends Alternative ? AlternativeAnc : never);
type AlternativeAnc = TrueAnc<Alternative>;
type CharacterClassAnc = TrueAnc<UnicodeSetsCharacterClass>;
type TrueAnc<T extends Node> = Anc6<GetParent<T>>;
type GetParent<T extends Node> = NonNullable<T["parent"]>;
type Anc6<T extends Node> = T | Anc5<GetParent<T>>;
type Anc5<T extends Node> = T | Anc4<GetParent<T>>;
type Anc4<T extends Node> = T | Anc3<GetParent<T>>;
type Anc3<T extends Node> = T | Anc2<GetParent<T>>;
type Anc2<T extends Node> = T | Anc1<GetParent<T>>;
type Anc1<T extends Node> = T | GetParent<T>;
/**
* Returns whether any of the ancestors of the given node fulfills the given condition.
*
* If the given condition is an AST node instead of a function, `hasSomeAncestor` will behave as if the condition
* function was `d => d === conditionNode`.
*
* The ancestors will be iterated in the order from closest to farthest.
* The condition function will not be called on the given node.
*/
export function hasSomeAncestor<T extends Node>(
node: T,
condition: ((ancestor: Ancestor<T>) => boolean) | Node
): boolean {
if (typeof condition === "function") {
return hasSomeAncestorFnImpl(node, condition);
} else {
return hasSomeAncestorNodeImpl(node, condition);
}
}
function hasSomeAncestorNodeImpl<T extends Node>(node: T, condition: Node): boolean {
let parent: Ancestor<Node> | null = node.parent;
while (parent) {
if (parent === condition) {
return true;
}
parent = parent.parent;
}
return false;
}
function hasSomeAncestorFnImpl<T extends Node>(node: T, condition: (ancestor: Ancestor<T>) => boolean): boolean {
let parent: Ancestor<Node> | null = node.parent;
while (parent) {
if (condition(parent as Ancestor<T>)) {
return true;
}
parent = parent.parent;
}
return false;
}
/**
* Returns the type of all possible ancestor nodes of the given node type. This trivially includes the given type.
*
* @see {@link hasSomeDescendant}
*/
export type Descendant<T extends Node> = T | DescendantsImpl<T>;
type DescendantsImpl<T extends Node> = Dec1<GetChildren<T>>;
type Dec1<T extends Node> = T | Dec2<GetChildren<T>>;
type Dec2<T extends Node> = T | GetChildren<T>;
type GetChildren<T extends Node> =
| (T extends RegExpLiteral ? Flags | Pattern | Element : never)
| (T extends Alternative | CapturingGroup | Group | LookaroundAssertion | Quantifier | Pattern
? Alternative | Element
: never)
| (T extends Alternative ? Element : never)
| (T extends ClassRangesCharacterClass ? ClassRangesCharacterClassElement : never)
| (T extends CharacterClassRange ? Character : never)
// unicode sets
| (T extends UnicodeSetsCharacterClass | ExpressionCharacterClass | ExpressionCharacterClass["expression"]
? UnicodeSetsDescendants
: never)
| (T extends ClassStringDisjunction ? StringAlternative : never)
| (T extends StringAlternative ? Character : never);
type UnicodeSetsDescendants =
| ClassSetOperand
| UnicodeSetsCharacterClassElement
| UnicodeSetsCharacterClass
| ExpressionCharacterClass
| ExpressionCharacterClass["expression"];
/**
* Returns whether any of the descendants of the given node fulfill the given condition.
*
* The descendants will be iterated in a DFS top-to-bottom manner from left to right with the first node being the
* given node.
*
* If the given condition is an AST node instead of a function, `hasSomeDescendant` will behave as if the condition
* function was `d => d === conditionNode`.
*
* This function is short-circuited, so as soon as any `condition` returns `true`, `true` will be returned.
*
* @param node
* @param condition
* @param descentConditionFn An optional function to decide whether the descendant of the given node will be checked as
* well.
*
* This function will be called with some node only after `condition` has returned `false` for this node.
*/
export function hasSomeDescendant<T extends Node>(
node: T,
condition: ((descendant: Descendant<T>) => boolean) | Node,
descentConditionFn?: (descendant: Descendant<T>) => boolean
): boolean {
if (typeof condition === "function") {
return hasSomeDescendantImpl(node, condition as never, descentConditionFn as never);
} else {
if (descentConditionFn) {
return hasSomeDescendantImpl(node, d => d === condition, descentConditionFn as never);
} else {
// instead of checking the O(n) descendant nodes of `node`, we can instead check the O(log n) ancestor
// nodes of `condition`
return node === condition || hasSomeAncestor(condition, node);
}
}
}
function hasSomeDescendantImpl(
node: Node,
conditionFn: (descendant: Descendant<Node>) => boolean,
descentConditionFn: (descendant: Descendant<Node>) => boolean | undefined
): boolean {
if (conditionFn(node)) {
return true;
}
if (descentConditionFn && !descentConditionFn(node)) {
return false;
}
switch (node.type) {
case "Alternative":
case "CharacterClass":
case "StringAlternative":
return node.elements.some(e => hasSomeDescendantImpl(e, conditionFn, descentConditionFn));
case "Assertion":
if (node.kind === "lookahead" || node.kind === "lookbehind") {
return node.alternatives.some(a => hasSomeDescendantImpl(a, conditionFn, descentConditionFn));
}
return false;
case "CapturingGroup":
case "ClassStringDisjunction":
case "Group":
case "Pattern":
return node.alternatives.some(a => hasSomeDescendantImpl(a, conditionFn, descentConditionFn));
case "ClassIntersection":
case "ClassSubtraction":
return (
hasSomeDescendantImpl(node.left, conditionFn, descentConditionFn) ||
hasSomeDescendantImpl(node.right, conditionFn, descentConditionFn)
);
case "ExpressionCharacterClass":
return hasSomeDescendantImpl(node.expression, conditionFn, descentConditionFn);
case "CharacterClassRange":
return (
hasSomeDescendantImpl(node.min, conditionFn, descentConditionFn) ||
hasSomeDescendantImpl(node.max, conditionFn, descentConditionFn)
);
case "Quantifier":
return hasSomeDescendantImpl(node.element, conditionFn, descentConditionFn);
case "RegExpLiteral":
return (
hasSomeDescendantImpl(node.pattern, conditionFn, descentConditionFn) ||
hasSomeDescendantImpl(node.flags, conditionFn, descentConditionFn)
);
case "Backreference":
case "Character":
case "CharacterSet":
case "Flags":
return false;
default:
return assertNever(node);
}
}
/**
* Returns the one-based number of the given capturing group.
*
* This is the number needed to refer to the capturing group via backreferences.
*/
export function getCapturingGroupNumber(group: CapturingGroup): number {
let found = 0;
try {
visitRegExpAST(getPattern(group), {
onCapturingGroupEnter(node) {
found++;
if (node === group) {
// throw an error to end early
throw new Error();
}
},
});
throw new Error("Unable to find the given capturing group in its parent pattern.");
} catch (error) {
return found;
}
}
/**
* Returns the pattern node of the JS RegExp of a given node.
*
* This operation is guaranteed to always success for all node types except for flags nodes. Flags nodes have an
* optional `parent` which, if not set, means that this function can't access the pattern node. If the function can't
* access the pattern node from a flags node, an error will be thrown.
*/
export function getPattern(node: Node): Pattern {
switch (node.type) {
case "RegExpLiteral":
return node.pattern;
case "Pattern":
return node;
case "Flags":
if (node.parent) {
return node.parent.pattern;
} else {
throw new Error("Unable to find the pattern of flags without a RegExp literal.");
}
default: {
let p:
| LookaroundAssertion
| Quantifier
| Group
| CapturingGroup
| CharacterClass
| Alternative
| CharacterClassRange
| ExpressionCharacterClass
| ExpressionCharacterClass["expression"]
| ClassStringDisjunction
| StringAlternative
| Pattern = node.parent;
while (p.type !== "Pattern") {
p = p.parent;
}
return p;
}
}
}
/**
* The correct matching direction of alternatives. This can be either `ltr` (left to right) or `rtl` (right to left).
*
* `ltr` is the matching direction of lookaheads and the default matching direction of JavaScript RegExps. `rtl` is the
* matching direction of lookbehinds.
*
* The current matching direction of an element is determined by the closest lookaround (lookahead or lookbehind)
* ancestor. If the closest lookaround ancestor is a lookahead, the matching direction is `ltr`. Likewise, if it's a
* lookbehind, it's `rtl`. If an element is not a descendant of a lookaround, the default matching direction `ltr` is
* assumed.
*
* @see {@link getMatchingDirection}
* @see {@link invertMatchingDirection}
* @see {@link getMatchingDirectionFromAssertionKind}
*/
export type MatchingDirection = "ltr" | "rtl";
/**
* This extends the {@link MatchingDirection} type to allow unknown matching
* directions.
*
* This is useful when the matching direction of an element/alternative cannot
* be known with 100% certainty.
*/
export type OptionalMatchingDirection = MatchingDirection | "unknown";
/**
* Returns the direction which which the given node will be matched relative to the closest parent alternative.
*
* If the given node is a lookaround, then the result of `getMatchingDirection(lookaround)` will be the same as
* `getMatchingDirection(lookaround.parent)`.
*/
export function getMatchingDirection(node: Node): MatchingDirection {
let closestLookaround: LookaroundAssertion | undefined;
hasSomeAncestor(node, a => {
if (a.type === "Assertion") {
closestLookaround = a;
return true;
}
return false;
});
if (closestLookaround === undefined) {
// left-to-right matching is assumed
return "ltr";
} else if (closestLookaround.kind === "lookahead") {
return "ltr";
} else {
return "rtl";
}
}
/**
* Returns the opposite matching direction of the given matching direction.
*
* If `ltr` is given, `rtl` will be returned and vise versa.
*/
export function invertMatchingDirection(direction: MatchingDirection): MatchingDirection {
return direction === "ltr" ? "rtl" : "ltr";
}
/**
* Converts a given assertion kind into a matching direction.
*
* For lookaheads and lookbehinds, the returned matching direction will be the matching direction of their children.
* I.e. the result of `lookahead` is `ltr` and the result of `lookbehind` is `rtl`.
*
* For edge assertions (`^` and `$`), the returned value is the direction of the character the edge assertion asserts.
* I.e. the result of `^` is `rtl` (because it asserts the previous character) and the result of `$` is `ltr` (because
* it asserts the next character).
*/
export function getMatchingDirectionFromAssertionKind(
kind: LookaroundAssertion["kind"] | EdgeAssertion["kind"]
): MatchingDirection {
return kind === "end" || kind === "lookahead" ? "ltr" : "rtl";
}
/**
* Returns whether the given backreference will always be replaced with the empty string.
*
* There are two reasons why a backreference might always be replaced with the empty string:
*
* 1. The referenced capturing group does not consume characters.
*
* This is the trivial case. If the referenced capturing group never consumes any characters, then a backreference to
* that group must be replaced with the empty string.
*
* E.g. `/(\b)a\1/`
*
* 2. The backreference is not after the referenced capturing group.
*
* A backreference can only be replaced with a non-empty string if the referenced capturing group has captured text
* before the backreference is matched. There are multiple reasons why the capturing group might be unable to capture
* text before a backreference to it is reached.
*
* - The capturing group might be in a different alternative. E.g. `/(a)b|\1/`.
* - The backreference might be *inside* the capturing group. E.g. `/(a\1)/`.
* - The backreference might be before the capturing group. E.g. `/\1(a)/`, `/(?:\1(a))+/`, `/(?<=(a)\1)b/`
*/
export function isEmptyBackreference(backreference: Backreference, flags: ReadonlyFlags): boolean {
const groups = getReferencedGroupsFromBackreference(backreference);
if (groups.length === 0) return true;
const backRefAncestors = new Set<Node>();
for (let a: Node | null = backreference; a; a = a.parent) {
backRefAncestors.add(a);
}
// Now for the hard part:
// If there exists a path through the regular expression which connect the group and the backreference, then
// the backreference can capture the group iff we only move up, down, or right relative to the group.
function findBackreference(node: CapturingGroup | Group | LookaroundAssertion | Quantifier): boolean {
const parent = node.parent;
switch (parent.type) {
case "Alternative": {
// if any elements right to the given node contain or are the backreference, we found it.
const index = parent.elements.indexOf(node);
// we have to take the current matching direction into account
let next;
if (getMatchingDirection(node) === "ltr") {
// the next elements to match will be right to the given node
next = parent.elements.slice(index + 1);
} else {
// the next elements to match will be left to the given node
next = parent.elements.slice(0, index);
}
if (next.some(e => backRefAncestors.has(e))) {
return true;
}
// no luck. let's go up!
const parentParent = parent.parent;
if (parentParent.type === "Pattern") {
// can't go up.
return false;
} else if (parentParent.type === "Assertion" && parentParent.negate) {
// The captured text of a capturing group will be reset after leaving a negated lookaround
return false;
} else {
return findBackreference(parentParent);
}
}
case "Quantifier":
return findBackreference(parent);
}
}
return groups.every(group => !findBackreference(group) || isZeroLength(group, flags));
}
/**
* Returns whether the given backreference is a strict backreference.
*
* Strict backreferences are backreferences that are always matched __after__ the referenced group was matched. If there
* exists any path that goes through a backreference but not through the referenced capturing group, that backreference
* is not strict.
*
* ## Examples
*
* In the follow examples, `\1` is a strict backreference:
*
* - `/(a)\1/`
* - `/(a)(?:b|\1)/`
* - `/(a)\1?/`
* - `/(?<=\1(a))b/`
*
* In the follow examples, `\1` is not a strict backreference:
*
* - `/(a)|\1/`
* - `/(?:(a)|b)\1/`
* - `/(a)?\1/`
* - `/(?<=(a)\1)b/`
* - `/(?!(a)).\1/`
*/
export function isStrictBackreference(backreference: Backreference): boolean {
const groups = getReferencedGroupsFromBackreference(backreference);
if (groups.length === 0) return false;
const backRefAncestors = new Set<Node>();
for (let a: Node | null = backreference; a; a = a.parent) {
backRefAncestors.add(a);
}
function findBackreference(node: CapturingGroup | Group | LookaroundAssertion | Quantifier): boolean {
const parent = node.parent;
switch (parent.type) {
case "Alternative": {
// if any elements right to the given node contain or are the backreference, we found it.
const index = parent.elements.indexOf(node);
// we have to take the current matching direction into account
let next;
if (getMatchingDirection(node) === "ltr") {
// the next elements to match will be right to the given node
next = parent.elements.slice(index + 1);
} else {
// the next elements to match will be left to the given node
next = parent.elements.slice(0, index);
}
if (next.some(e => backRefAncestors.has(e))) {
return true;
}
// no luck. let's go up!
const parentParent = parent.parent;
if (parentParent.type === "Pattern") {
// can't go up.
return false;
} else if (parentParent.type === "Assertion" && parentParent.negate) {
// The captured text of a capturing group will be reset after leaving a negated lookaround
return false;
} else {
if (
parentParent.alternatives.length > 1 &&
parentParent.alternatives.some(
alternative =>
!hasSomeDescendant(alternative, node => {
return node.type === "CapturingGroup" && groups.includes(node);
})
)
) {
// e.g.: (?:a|(a))+b\1
return false;
}
return findBackreference(parentParent);
}
}
case "Quantifier":
if (parent.min === 0) {
// e.g.: (a+)?b\1
return false;
}
return findBackreference(parent);
}
}
return groups.every(findBackreference);
}
/**
* Given a node type `N`, this will map to whether a node of type `N` can contain a capturing group.
*/
export type ContainsCapturingGroup<N extends Node> = N extends
| CharacterClassElement
| CharacterClass
| CharacterSet
| Backreference
| EdgeAssertion
| WordBoundaryAssertion
| Flags
? false
: N extends CapturingGroup
? true
: boolean;
/**
* Returns whether the given node contains or is a capturing group.
*
* This function is guaranteed to behave in the same way as:
*
* ```js
* hasSomeDescendant(node, d => d.type === "CapturingGroup")
* ```
*/
export function containsCapturingGroup<N extends Node>(node: N): ContainsCapturingGroup<N> {
return hasSomeDescendant(node, isCapturingGroup) as ContainsCapturingGroup<N>;
}
function isCapturingGroup(node: Node): node is CapturingGroup {
return node.type === "CapturingGroup";
}
/**
* The length range of string accepted. All string that are accepted by have a length of `min <= length <= max`.
*
* @see {@link getLengthRange}
*/
export interface LengthRange {
readonly min: number;
readonly max: number;
}
const ZERO_LENGTH_RANGE: LengthRange = { min: 0, max: 0 };
const ONE_LENGTH_RANGE: LengthRange = { min: 1, max: 1 };
/**
* Returns how many characters the given element can consume at most and has to consume at least.
*
* Note that character classes are not parsed by this function and are assumed to be non-empty.
*
* ## Backreferences
*
* While {@link isPotentiallyZeroLength} generally assumes the worst-case for backreferences that references capturing group
* outside the given element, this function does not/cannot. The length range of a backreference only depends on the
* referenced capturing group and the relative positions of the backreference and the capturing group within the
* pattern. It does not depend on the given element.
*
* This is an important distinction because it means that `isPotentiallyZeroLength(e) -> getLengthRange(e).min == 0` is
* guaranteed but `getLengthRange(e).min == 0 -> isPotentiallyZeroLength(e)` is only guaranteed if `e` does not contain
* backreferences.
*
* @throws {RangeError} if an empty array of alternatives is given.
*
* @see {@link isZeroLength}
* @see {@link isPotentiallyZeroLength}
* @see {@link isEmpty}
* @see {@link isPotentiallyEmpty}
*/
export function getLengthRange(
element: Element | CharacterElement | Alternative | readonly Alternative[],
flags: ReadonlyFlags
): LengthRange {
if (isReadonlyArray(element)) {
return getLengthRangeAlternativesImpl(element, flags);
} else {
return getLengthRangeElementImpl(element, flags);
}
}
function getLengthRangeAlternativesImpl(
alternatives: readonly (Element | CharacterElement | Alternative)[],
flags: ReadonlyFlags
): LengthRange {
let min = Infinity;
let max = 0;
for (const a of alternatives) {
const eRange = getLengthRangeElementImpl(a, flags);
min = Math.min(min, eRange.min);
max = Math.max(max, eRange.max);
}
if (min > max) {
throw new RangeError("Expected the alternatives array to have at least one alternative.");
} else {
return { min, max };
}
}
function unicodeSetToLengthRange(set: JS.UnicodeSet): LengthRange {
const range = set.getLengthRange();
if (!range) {