|
| 1 | +import type { Rule } from "eslint" |
| 2 | +import { hasSomeDescendant } from "regexp-ast-analysis" |
| 3 | +import type { RegExpVisitor } from "regexpp/visitor" |
| 4 | +import type { RegExpContext } from "../utils" |
| 5 | +import { canUnwrapped, createRule, defineRegexpVisitor } from "../utils" |
| 6 | + |
| 7 | +export default createRule("no-zero-quantifier", { |
| 8 | + meta: { |
| 9 | + docs: { |
| 10 | + description: "disallow quantifiers with a maximum of zero", |
| 11 | + // TODO Switch to recommended in the major version. |
| 12 | + // recommended: true, |
| 13 | + recommended: false, |
| 14 | + }, |
| 15 | + schema: [], |
| 16 | + messages: { |
| 17 | + unexpected: |
| 18 | + "Unexpected zero quantifier. The quantifier and its quantified element can be removed without affecting the pattern.", |
| 19 | + withCapturingGroup: |
| 20 | + "Unexpected zero quantifier. The quantifier and its quantified element do not affecting the pattern. Try to remove the elements but be careful because it contains at least one capturing group.", |
| 21 | + |
| 22 | + // suggestions |
| 23 | + remove: "Remove this zero quantifier.", |
| 24 | + }, |
| 25 | + type: "suggestion", // "problem", |
| 26 | + }, |
| 27 | + create(context) { |
| 28 | + /** |
| 29 | + * Create visitor |
| 30 | + */ |
| 31 | + function createVisitor( |
| 32 | + regexpContext: RegExpContext, |
| 33 | + ): RegExpVisitor.Handlers { |
| 34 | + const { |
| 35 | + node, |
| 36 | + getRegexpLocation, |
| 37 | + fixReplaceNode, |
| 38 | + patternAst, |
| 39 | + } = regexpContext |
| 40 | + |
| 41 | + return { |
| 42 | + onQuantifierEnter(qNode) { |
| 43 | + if (qNode.max === 0) { |
| 44 | + const containCapturingGroup = hasSomeDescendant( |
| 45 | + qNode, |
| 46 | + (n) => n.type === "CapturingGroup", |
| 47 | + ) |
| 48 | + |
| 49 | + if (containCapturingGroup) { |
| 50 | + context.report({ |
| 51 | + node, |
| 52 | + loc: getRegexpLocation(qNode), |
| 53 | + messageId: "withCapturingGroup", |
| 54 | + }) |
| 55 | + } else { |
| 56 | + const suggest: Rule.SuggestionReportDescriptor[] = [] |
| 57 | + if (patternAst.raw === qNode.raw) { |
| 58 | + suggest.push({ |
| 59 | + messageId: "remove", |
| 60 | + fix: fixReplaceNode(qNode, "(?:)"), |
| 61 | + }) |
| 62 | + } else if (canUnwrapped(qNode, "")) { |
| 63 | + suggest.push({ |
| 64 | + messageId: "remove", |
| 65 | + fix: fixReplaceNode(qNode, ""), |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + context.report({ |
| 70 | + node, |
| 71 | + loc: getRegexpLocation(qNode), |
| 72 | + messageId: "unexpected", |
| 73 | + suggest, |
| 74 | + }) |
| 75 | + } |
| 76 | + } |
| 77 | + }, |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return defineRegexpVisitor(context, { |
| 82 | + createVisitor, |
| 83 | + }) |
| 84 | + }, |
| 85 | +}) |
0 commit comments