-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathno-dupe-disjunctions.ts
1392 lines (1242 loc) · 43.9 KB
/
no-dupe-disjunctions.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 type {
Alternative,
CapturingGroup,
CharacterClassElement,
Group,
LookaroundAssertion,
Node,
Pattern,
Quantifier,
} from "@eslint-community/regexpp/ast"
import type { RegExpVisitor } from "@eslint-community/regexpp/visitor"
import type { Rule } from "eslint"
import type { Expression, FiniteAutomaton, NoParent, ReadonlyNFA } from "refa"
import {
Transformers,
DFA,
NFA,
JS,
visitAst,
transform,
isDisjointWith,
} from "refa"
import type { ReadonlyFlags } from "regexp-ast-analysis"
import {
hasSomeAncestor,
hasSomeDescendant,
getMatchingDirection,
getEffectiveMaximumRepetition,
canReorder,
} from "regexp-ast-analysis"
import type { RegExpContext } from "../utils"
import {
createRule,
defineRegexpVisitor,
fixRemoveCharacterClassElement,
fixRemoveAlternative,
fixRemoveStringAlternative,
} from "../utils"
import { getAllowedCharRanges, inRange } from "../utils/char-ranges"
import { UsageOfPattern } from "../utils/get-usage-of-pattern"
import { mention, mentionChar } from "../utils/mention"
import type { NestedAlternative } from "../utils/partial-parser"
import { PartialParser } from "../utils/partial-parser"
import { getParser, assertValidFlags } from "../utils/refa"
import { isCoveredNode, isEqualNodes } from "../utils/regexp-ast"
import { assertNever } from "../utils/util"
type ParentNode = Group | CapturingGroup | Pattern | LookaroundAssertion
/**
* Returns whether the node or the elements of the node are effectively
* quantified with a star.
*/
function isStared(node: Node): boolean {
let max = getEffectiveMaximumRepetition(node)
if (node.type === "Quantifier") {
max *= node.max
}
return max > 10
}
/**
* Check has after pattern
*/
function hasNothingAfterNode(node: ParentNode): boolean {
const md = getMatchingDirection(node)
for (
let p:
| Group
| Pattern
| CapturingGroup
| LookaroundAssertion
| Quantifier
| Alternative = node;
;
p = p.parent
) {
if (p.type === "Assertion" || p.type === "Pattern") {
return true
}
if (p.type !== "Alternative") {
const parent: Quantifier | Alternative = p.parent
if (parent.type === "Quantifier") {
if (parent.max > 1) {
return false
}
} else {
const lastIndex: number =
md === "ltr" ? parent.elements.length - 1 : 0
if (parent.elements[lastIndex] !== p) {
return false
}
}
}
}
}
/**
* Returns whether the given RE AST contains assertions.
*/
function containsAssertions(expression: NoParent<Expression>): boolean {
try {
visitAst(expression, {
onAssertionEnter() {
throw new Error()
},
})
return false
} catch (_error) {
return true
}
}
/**
* Returns whether the given RE AST contains assertions or unknowns.
*/
function containsAssertionsOrUnknowns(
expression: NoParent<Expression>,
): boolean {
try {
visitAst(expression, {
onAssertionEnter() {
throw new Error()
},
onUnknownEnter() {
throw new Error()
},
})
return false
} catch (_error) {
return true
}
}
/**
* Returns whether the given nodes contains any features that cannot be
* expressed by pure regular expression. This mainly includes assertions and
* backreferences.
*/
function isNonRegular(node: Node): boolean {
return hasSomeDescendant(
node,
(d) => d.type === "Assertion" || d.type === "Backreference",
)
}
/**
* Create an NFA from the given element.
*
* The `partial` value determines whether the NFA perfectly represents the given
* element. Some elements might contain features that cannot be represented
* using NFA in which case a partial NFA will be created (e.g. the NFA of
* `a|\bfoo\b` is equivalent to the NFA of `a`).
*/
function toNFA(
parser: JS.Parser,
element: JS.ParsableElement,
): { nfa: NFA; partial: boolean } {
try {
const { expression, maxCharacter } = parser.parseElement(element, {
backreferences: "unknown",
assertions: "parse",
})
let e
if (containsAssertions(expression)) {
e = transform(
Transformers.simplify({
ignoreAmbiguity: true,
ignoreOrder: true,
}),
expression,
)
} else {
e = expression
}
return {
nfa: NFA.fromRegex(
e,
{ maxCharacter },
{ assertions: "disable", unknowns: "disable" },
),
partial: containsAssertionsOrUnknowns(e),
}
} catch (_error) {
return {
nfa: NFA.empty({
maxCharacter: parser.maxCharacter,
}),
partial: true,
}
}
}
/**
* Yields all nested alternatives in the given root alternative.
*
* This will yield actual alternative nodes as well as character class
* elements. The elements of a non-negated character class (e.g. `[abc]`) can
* be thought of as an alternative. That's why they are returned.
*
* Note: If a group contains only a single alternative, then this group won't
* be yielded by this function. This is because the partial NFA of that single
* alternative is that same as the partial NFA of the parent alternative of the
* group. A similar condition applies for the elements of character classes.
*/
function* iterateNestedAlternatives(
alternative: Alternative,
): Iterable<NestedAlternative> {
for (const e of alternative.elements) {
if (e.type === "Group" || e.type === "CapturingGroup") {
for (const a of e.alternatives) {
if (e.alternatives.length > 1) {
yield a
}
yield* iterateNestedAlternatives(a)
}
}
if (e.type === "CharacterClass" && !e.negate) {
const nested: NestedAlternative[] = []
// eslint-disable-next-line func-style -- x
const addToNested = (charElement: CharacterClassElement) => {
switch (charElement.type) {
case "CharacterClassRange": {
const min = charElement.min
const max = charElement.max
if (min.value === max.value) {
nested.push(charElement)
} else if (min.value + 1 === max.value) {
nested.push(min, max)
} else {
nested.push(charElement, min, max)
}
break
}
case "ClassStringDisjunction": {
nested.push(...charElement.alternatives)
break
}
case "CharacterClass": {
if (!charElement.negate) {
charElement.elements.forEach(addToNested)
} else {
nested.push(charElement)
}
break
}
case "Character":
case "CharacterSet":
case "ExpressionCharacterClass": {
nested.push(charElement)
break
}
default:
throw assertNever(charElement)
}
}
e.elements.forEach(addToNested)
if (nested.length > 1) yield* nested
}
}
}
/**
* A nested alternative + the partial NFA of that nested alternatives.
*
* The partial NFA is generated by {@link PartialParser}.
*/
interface PartialAlternative {
nested: NestedAlternative
nfa: NFA
}
/**
* This will return all partial alternatives.
*
* A partial alternative is the NFA of the given alternative but with one
* nested alternative missing.
*/
function* iteratePartialAlternatives(
alternative: Alternative,
parser: JS.Parser,
): Iterable<PartialAlternative> {
if (isNonRegular(alternative)) {
return
}
const maxCharacter = parser.maxCharacter
const partialParser = new PartialParser(parser, {
assertions: "throw",
backreferences: "throw",
})
for (const nested of iterateNestedAlternatives(alternative)) {
try {
const expression = partialParser.parse(alternative, nested)
const nfa = NFA.fromRegex(expression, { maxCharacter })
yield { nested, nfa }
} catch (_error) {
// ignore error and skip this
}
}
}
function unionAll(nfas: readonly ReadonlyNFA[]): ReadonlyNFA {
if (nfas.length === 0) {
throw new Error("Cannot union 0 NFAs.")
} else if (nfas.length === 1) {
return nfas[0]
}
const total = nfas[0].copy()
for (let i = 1; i < nfas.length; i++) {
total.union(nfas[i])
}
return total
}
const MAX_DFA_NODES = 100_000
function isSubsetOf(
superset: ReadonlyNFA,
subset: ReadonlyNFA,
): boolean | null {
try {
const a = DFA.fromIntersection(
superset,
subset,
new DFA.LimitedNodeFactory(MAX_DFA_NODES),
)
const b = DFA.fromFA(subset, new DFA.LimitedNodeFactory(MAX_DFA_NODES))
a.minimize()
b.minimize()
return a.structurallyEqual(b)
} catch (_error) {
return null
}
}
const enum SubsetRelation {
none,
leftEqualRight,
leftSubsetOfRight,
leftSupersetOfRight,
unknown,
}
function getSubsetRelation(
left: ReadonlyNFA,
right: ReadonlyNFA,
): SubsetRelation {
try {
const inter = DFA.fromIntersection(
left,
right,
new DFA.LimitedNodeFactory(MAX_DFA_NODES),
)
inter.minimize()
const l = DFA.fromFA(left, new DFA.LimitedNodeFactory(MAX_DFA_NODES))
l.minimize()
const r = DFA.fromFA(right, new DFA.LimitedNodeFactory(MAX_DFA_NODES))
r.minimize()
const subset = l.structurallyEqual(inter)
const superset = r.structurallyEqual(inter)
if (subset && superset) {
return SubsetRelation.leftEqualRight
} else if (subset) {
return SubsetRelation.leftSubsetOfRight
} else if (superset) {
return SubsetRelation.leftSupersetOfRight
}
return SubsetRelation.none
} catch (_error) {
return SubsetRelation.unknown
}
}
/**
* The `getSubsetRelation` function assumes that both NFAs perfectly represent
* their language.
*
* This function adjusts their subset relation to account for partial NFAs.
*/
function getPartialSubsetRelation(
left: ReadonlyNFA,
leftIsPartial: boolean,
right: ReadonlyNFA,
rightIsPartial: boolean,
): SubsetRelation {
const relation = getSubsetRelation(left, right)
if (!leftIsPartial && !rightIsPartial) {
return relation
}
if (
relation === SubsetRelation.none ||
relation === SubsetRelation.unknown
) {
return relation
}
if (leftIsPartial && !rightIsPartial) {
switch (relation) {
case SubsetRelation.leftEqualRight:
return SubsetRelation.leftSupersetOfRight
case SubsetRelation.leftSubsetOfRight:
return SubsetRelation.none
case SubsetRelation.leftSupersetOfRight:
return SubsetRelation.leftSupersetOfRight
default:
return assertNever(relation)
}
}
if (rightIsPartial && !leftIsPartial) {
switch (relation) {
case SubsetRelation.leftEqualRight:
return SubsetRelation.leftSubsetOfRight
case SubsetRelation.leftSubsetOfRight:
return SubsetRelation.leftSubsetOfRight
case SubsetRelation.leftSupersetOfRight:
return SubsetRelation.none
default:
return assertNever(relation)
}
}
// both are partial
return SubsetRelation.none
}
/**
* Returns the regex source of the given FA.
*/
function faToSource(fa: FiniteAutomaton, flags: ReadonlyFlags): string {
try {
assertValidFlags(flags)
return JS.toLiteral(fa.toRegex(), { flags }).source
} catch (_error) {
return "<ERROR>"
}
}
interface ResultBase {
alternative: Alternative
others: Alternative[]
}
interface DuplicateResult extends ResultBase {
type: "Duplicate"
others: [Alternative]
}
interface SubsetResult extends ResultBase {
type: "Subset"
}
interface NestedSubsetResult extends ResultBase {
type: "NestedSubset"
nested: NestedAlternative
}
interface PrefixSubsetResult extends ResultBase {
type: "PrefixSubset"
}
interface PrefixNestedSubsetResult extends ResultBase {
type: "PrefixNestedSubset"
nested: NestedAlternative
}
interface SupersetResult extends ResultBase {
type: "Superset"
}
interface OverlapResult extends ResultBase {
type: "Overlap"
overlap: NFA
}
type Result =
| DuplicateResult
| SubsetResult
| NestedSubsetResult
| PrefixSubsetResult
| PrefixNestedSubsetResult
| SupersetResult
| OverlapResult
interface Options {
parser: JS.Parser
hasNothingAfter: boolean
fastAst: boolean
noNfa: boolean
ignoreOverlap: boolean
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplicationAstFast(
alternatives: Alternative[],
flags: ReadonlyFlags,
): Iterable<Result> {
// eslint-disable-next-line func-style -- x
const shortCircuit: Parameters<typeof isEqualNodes>[3] = (a) => {
return a.type === "CapturingGroup" ? false : null
}
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
for (let j = 0; j < i; j++) {
const other = alternatives[j]
if (isEqualNodes(other, alternative, flags, shortCircuit)) {
yield { type: "Duplicate", alternative, others: [other] }
}
}
}
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplicationAst(
alternatives: Alternative[],
flags: ReadonlyFlags,
hasNothingAfter: boolean,
): Iterable<Result> {
const isCoveredOptions: Parameters<typeof isCoveredNode>[2] = {
flags,
canOmitRight: hasNothingAfter,
}
const isCoveredOptionsNoPrefix: Parameters<typeof isCoveredNode>[2] = {
flags,
canOmitRight: false,
}
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
for (let j = 0; j < i; j++) {
const other = alternatives[j]
if (isCoveredNode(other, alternative, isCoveredOptions)) {
if (isEqualNodes(other, alternative, flags)) {
yield {
type: "Duplicate",
alternative,
others: [other],
}
} else if (
hasNothingAfter &&
!isCoveredNode(other, alternative, isCoveredOptionsNoPrefix)
) {
yield {
type: "PrefixSubset",
alternative,
others: [other],
}
} else {
yield { type: "Subset", alternative, others: [other] }
}
}
}
}
}
/**
* Tries to find duplication in the given alternatives.
*
* It will search for prefix duplications. I.e. the alternative `ab` in `a|ab`
* is a duplicate of `a` because if `ab` accepts, `a` will have already accepted
* the input string. This makes `ab` effectively useless.
*
* This operation will modify the given NFAs.
*/
function* findPrefixDuplicationNfa(
alternatives: [NFA, boolean, Alternative][],
parser: JS.Parser,
): Iterable<Result> {
if (alternatives.length === 0) {
return
}
// For two alternatives `A|B`, `B` is useless if `B` is a subset of `A[^]*`
const all = NFA.all({ maxCharacter: alternatives[0][0].maxCharacter })
for (let i = 0; i < alternatives.length; i++) {
const [nfa, partial, alternative] = alternatives[i]
if (!partial) {
const overlapping = alternatives
.slice(0, i)
.filter(([otherNfa]) => !isDisjointWith(nfa, otherNfa))
if (overlapping.length >= 1) {
const othersNfa = unionAll(overlapping.map(([n]) => n))
const others = overlapping.map(([, , a]) => a)
// Only checking for a subset relation is sufficient here.
// Duplicates are VERY unlikely. (Who would use alternatives
// like `a|a[^]*`?)
if (isSubsetOf(othersNfa, nfa)) {
yield { type: "PrefixSubset", alternative, others }
} else {
const nested = tryFindNestedSubsetResult(
overlapping.map((o) => [o[0], o[2]]),
othersNfa,
alternative,
parser,
)
if (nested) {
yield { ...nested, type: "PrefixNestedSubset" }
}
}
}
}
nfa.append(all)
}
}
/**
* Tries to find duplication in the given alternatives.
*/
function* findDuplicationNfa(
alternatives: Alternative[],
flags: ReadonlyFlags,
{ hasNothingAfter, parser, ignoreOverlap }: Options,
): Iterable<Result> {
const previous: [NFA, boolean, Alternative][] = []
for (let i = 0; i < alternatives.length; i++) {
const alternative = alternatives[i]
const { nfa, partial } = toNFA(parser, alternative)
const overlapping = previous.filter(
([otherNfa]) => !isDisjointWith(nfa, otherNfa),
)
if (overlapping.length >= 1) {
const othersNfa = unionAll(overlapping.map(([n]) => n))
const othersPartial = overlapping.some(([, p]) => p)
const others = overlapping.map(([, , a]) => a)
const relation = getPartialSubsetRelation(
nfa,
partial,
othersNfa,
othersPartial,
)
switch (relation) {
case SubsetRelation.leftEqualRight:
if (others.length === 1) {
// only return "duplicate" if there is only one other
// alternative
yield {
type: "Duplicate",
alternative,
others: [others[0]],
}
} else {
yield { type: "Subset", alternative, others }
}
break
case SubsetRelation.leftSubsetOfRight:
yield { type: "Subset", alternative, others }
break
case SubsetRelation.leftSupersetOfRight: {
const reorder = canReorder([alternative, ...others], flags)
if (reorder) {
// We are allowed to freely reorder the alternatives.
// This means that we can reverse the order of our
// alternatives to convert the superset into a subset.
for (const other of others) {
yield {
type: "Subset",
alternative: other,
others: [alternative],
}
}
} else {
yield { type: "Superset", alternative, others }
}
break
}
case SubsetRelation.none:
case SubsetRelation.unknown: {
const nested = tryFindNestedSubsetResult(
overlapping.map((o) => [o[0], o[2]]),
othersNfa,
alternative,
parser,
)
if (nested) {
yield nested
break
}
if (!ignoreOverlap) {
yield {
type: "Overlap",
alternative,
others,
overlap: NFA.fromIntersection(nfa, othersNfa),
}
}
break
}
default:
throw assertNever(relation)
}
}
previous.push([nfa, partial, alternative])
}
if (hasNothingAfter) {
yield* findPrefixDuplicationNfa(previous, parser)
}
}
/**
* Given an alternative and list of overlapping other alternatives, this will
* try to find a nested alternative within the given alternative such that the
* nested alternative is a subset of the other alternatives.
*/
function tryFindNestedSubsetResult(
others: [ReadonlyNFA, Alternative][],
othersNfa: ReadonlyNFA,
alternative: Alternative,
parser: JS.Parser,
): NestedSubsetResult | undefined {
const disjointElements = new Set<Node>()
for (const { nested, nfa: nestedNfa } of iteratePartialAlternatives(
alternative,
parser,
)) {
if (hasSomeAncestor(nested, (a) => disjointElements.has(a))) {
// there's no point in trying because the partial NFA of an
// ancestor of this nested alternative was disjoint with the
// target (others) NFA
continue
}
if (isDisjointWith(othersNfa, nestedNfa)) {
disjointElements.add(nested)
continue
}
if (isSubsetOf(othersNfa, nestedNfa)) {
return {
type: "NestedSubset",
alternative,
nested,
others: others
.filter((o) => !isDisjointWith(o[0], nestedNfa))
.map((o) => o[1]),
}
}
}
return undefined
}
/**
* Tries to find duplication in the given alternatives
*/
function* findDuplication(
alternatives: Alternative[],
flags: ReadonlyFlags,
options: Options,
): Iterable<Result> {
// AST-based approach
if (options.fastAst) {
yield* findDuplicationAstFast(alternatives, flags)
} else {
yield* findDuplicationAst(alternatives, flags, options.hasNothingAfter)
}
// NFA-based approach
if (!options.noNfa) {
yield* findDuplicationNfa(alternatives, flags, options)
}
}
const RESULT_TYPE_ORDER: Result["type"][] = [
"Duplicate",
"Subset",
"NestedSubset",
"PrefixSubset",
"PrefixNestedSubset",
"Superset",
"Overlap",
]
/**
* Returns an array of the given results that is sorted by result type from
* most important to least important.
*/
function deduplicateResults(
unsorted: Iterable<Result>,
{ reportExp }: FilterInfo,
): Result[] {
const results = [...unsorted].sort(
(a, b) =>
RESULT_TYPE_ORDER.indexOf(a.type) -
RESULT_TYPE_ORDER.indexOf(b.type),
)
const seen = new Map<Alternative, Result["type"]>()
return results.filter(({ alternative, type }) => {
const firstSeen = seen.get(alternative)
if (firstSeen === undefined) {
seen.set(alternative, type)
return true
}
if (
reportExp &&
firstSeen === "PrefixSubset" &&
type !== "PrefixSubset"
) {
// Prefix subset might overshadow some other results (Superset or
// Overlap) that report exponential backtracking. In this case, we
// want to report BOTH the Prefix subset and one Superset or
// Overlap.
seen.set(alternative, type)
return true
}
return false
})
}
function mentionNested(nested: NestedAlternative): string {
if (nested.type === "Alternative" || nested.type === "StringAlternative") {
return mention(nested)
}
return mentionChar(nested)
}
/**
* Returns a fix that removes the given alternative.
*/
function fixRemoveNestedAlternative(
context: RegExpContext,
alternative: NestedAlternative,
) {
switch (alternative.type) {
case "Alternative":
return fixRemoveAlternative(context, alternative)
case "StringAlternative":
return fixRemoveStringAlternative(context, alternative)
case "Character":
case "CharacterClassRange":
case "CharacterSet":
case "CharacterClass":
case "ExpressionCharacterClass":
case "ClassStringDisjunction": {
if (alternative.parent.type !== "CharacterClass") {
// This isn't supposed to happen. We can't just remove the only
// alternative of its parent
return () => null
}
return fixRemoveCharacterClassElement(context, alternative)
}
default:
throw assertNever(alternative)
}
}
const enum ReportOption {
all = "all",
trivial = "trivial",
interesting = "interesting",
}
const enum ReportExponentialBacktracking {
none = "none",
certain = "certain",
potential = "potential",
}
const enum ReportUnreachable {
certain = "certain",
potential = "potential",
}
const enum MaybeBool {
false = 0,
true = 1,
maybe = 2,
}
interface FilterInfo {
stared: MaybeBool
nothingAfter: MaybeBool
reportExp: boolean
reportPrefix: boolean
}
export default createRule("no-dupe-disjunctions", {
meta: {
docs: {
description: "disallow duplicate disjunctions",
category: "Possible Errors",
recommended: true,
},
hasSuggestions: true,
schema: [
{
type: "object",
properties: {
report: {
type: "string",
enum: ["all", "trivial", "interesting"],
},
reportExponentialBacktracking: {
enum: ["none", "certain", "potential"],
},
reportUnreachable: {
enum: ["certain", "potential"],
},
},
additionalProperties: false,
},
],
messages: {
duplicate:
"Unexpected duplicate alternative. This alternative can be removed.{{cap}}{{exp}}",
subset: "Unexpected useless alternative. This alternative is a strict subset of {{others}} and can be removed.{{cap}}{{exp}}",
nestedSubset:
"Unexpected useless element. All paths of {{root}} that go through {{nested}} are a strict subset of {{others}}. This element can be removed.{{cap}}{{exp}}",
prefixSubset:
"Unexpected useless alternative. This alternative is already covered by {{others}} and can be removed.{{cap}}",
prefixNestedSubset:
"Unexpected useless element. All paths of {{root}} that go through {{nested}} are already covered by {{others}}. This element can be removed.{{cap}}",
superset:
"Unexpected superset. This alternative is a superset of {{others}}. It might be possible to remove the other alternative(s).{{cap}}{{exp}}",
overlap:
"Unexpected overlap. This alternative overlaps with {{others}}. The overlap is {{expr}}.{{cap}}{{exp}}",
remove: "Remove the {{alternative}} {{type}}.",
replaceRange: "Replace {{range}} with {{replacement}}.",
},
type: "suggestion", // "problem",
},
create(context) {
const reportExponentialBacktracking: ReportExponentialBacktracking =
context.options[0]?.reportExponentialBacktracking ??
ReportExponentialBacktracking.potential
const reportUnreachable: ReportUnreachable =
context.options[0]?.reportUnreachable ?? ReportUnreachable.certain
const report: ReportOption =
context.options[0]?.report ?? ReportOption.trivial
const allowedRanges = getAllowedCharRanges(undefined, context)
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const { flags, node, getRegexpLocation, getUsageOfPattern } =
regexpContext
const parser = getParser(regexpContext)
/** Returns the filter information for the given node */
function getFilterInfo(parentNode: ParentNode): FilterInfo {
const usage = getUsageOfPattern()
let stared: MaybeBool
if (isStared(parentNode)) {
stared = MaybeBool.true
} else if (
usage === UsageOfPattern.partial ||
usage === UsageOfPattern.mixed
) {
stared = MaybeBool.maybe