1 | /**
|
---|
2 | * @fileoverview Look for useless escapes in strings and regexes
|
---|
3 | * @author Onur Temizkan
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const astUtils = require("./utils/ast-utils");
|
---|
9 | const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp");
|
---|
10 |
|
---|
11 | /**
|
---|
12 | * @typedef {import('@eslint-community/regexpp').AST.CharacterClass} CharacterClass
|
---|
13 | * @typedef {import('@eslint-community/regexpp').AST.ExpressionCharacterClass} ExpressionCharacterClass
|
---|
14 | */
|
---|
15 | //------------------------------------------------------------------------------
|
---|
16 | // Rule Definition
|
---|
17 | //------------------------------------------------------------------------------
|
---|
18 |
|
---|
19 | /**
|
---|
20 | * Returns the union of two sets.
|
---|
21 | * @param {Set} setA The first set
|
---|
22 | * @param {Set} setB The second set
|
---|
23 | * @returns {Set} The union of the two sets
|
---|
24 | */
|
---|
25 | function union(setA, setB) {
|
---|
26 | return new Set(function *() {
|
---|
27 | yield* setA;
|
---|
28 | yield* setB;
|
---|
29 | }());
|
---|
30 | }
|
---|
31 |
|
---|
32 | const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS);
|
---|
33 | const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]");
|
---|
34 | const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk"));
|
---|
35 |
|
---|
36 | /*
|
---|
37 | * Set of characters that require escaping in character classes in `unicodeSets` mode.
|
---|
38 | * ( ) [ ] { } / - \ | are ClassSetSyntaxCharacter
|
---|
39 | */
|
---|
40 | const REGEX_CLASSSET_CHARACTER_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("q/[{}|()-"));
|
---|
41 |
|
---|
42 | /*
|
---|
43 | * A single character set of ClassSetReservedDoublePunctuator.
|
---|
44 | * && !! ## $$ %% ** ++ ,, .. :: ;; << == >> ?? @@ ^^ `` ~~ are ClassSetReservedDoublePunctuator
|
---|
45 | */
|
---|
46 | const REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR = new Set("!#$%&*+,.:;<=>?@^`~");
|
---|
47 |
|
---|
48 | /** @type {import('../shared/types').Rule} */
|
---|
49 | module.exports = {
|
---|
50 | meta: {
|
---|
51 | type: "suggestion",
|
---|
52 |
|
---|
53 | docs: {
|
---|
54 | description: "Disallow unnecessary escape characters",
|
---|
55 | recommended: true,
|
---|
56 | url: "https://eslint.org/docs/latest/rules/no-useless-escape"
|
---|
57 | },
|
---|
58 |
|
---|
59 | hasSuggestions: true,
|
---|
60 |
|
---|
61 | messages: {
|
---|
62 | unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
|
---|
63 | removeEscape: "Remove the `\\`. This maintains the current functionality.",
|
---|
64 | removeEscapeDoNotKeepSemantics: "Remove the `\\` if it was inserted by mistake.",
|
---|
65 | escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character."
|
---|
66 | },
|
---|
67 |
|
---|
68 | schema: []
|
---|
69 | },
|
---|
70 |
|
---|
71 | create(context) {
|
---|
72 | const sourceCode = context.sourceCode;
|
---|
73 | const parser = new RegExpParser();
|
---|
74 |
|
---|
75 | /**
|
---|
76 | * Reports a node
|
---|
77 | * @param {ASTNode} node The node to report
|
---|
78 | * @param {number} startOffset The backslash's offset from the start of the node
|
---|
79 | * @param {string} character The uselessly escaped character (not including the backslash)
|
---|
80 | * @param {boolean} [disableEscapeBackslashSuggest] `true` if escapeBackslash suggestion should be turned off.
|
---|
81 | * @returns {void}
|
---|
82 | */
|
---|
83 | function report(node, startOffset, character, disableEscapeBackslashSuggest) {
|
---|
84 | const rangeStart = node.range[0] + startOffset;
|
---|
85 | const range = [rangeStart, rangeStart + 1];
|
---|
86 | const start = sourceCode.getLocFromIndex(rangeStart);
|
---|
87 |
|
---|
88 | context.report({
|
---|
89 | node,
|
---|
90 | loc: {
|
---|
91 | start,
|
---|
92 | end: { line: start.line, column: start.column + 1 }
|
---|
93 | },
|
---|
94 | messageId: "unnecessaryEscape",
|
---|
95 | data: { character },
|
---|
96 | suggest: [
|
---|
97 | {
|
---|
98 |
|
---|
99 | // Removing unnecessary `\` characters in a directive is not guaranteed to maintain functionality.
|
---|
100 | messageId: astUtils.isDirective(node.parent)
|
---|
101 | ? "removeEscapeDoNotKeepSemantics" : "removeEscape",
|
---|
102 | fix(fixer) {
|
---|
103 | return fixer.removeRange(range);
|
---|
104 | }
|
---|
105 | },
|
---|
106 | ...disableEscapeBackslashSuggest
|
---|
107 | ? []
|
---|
108 | : [
|
---|
109 | {
|
---|
110 | messageId: "escapeBackslash",
|
---|
111 | fix(fixer) {
|
---|
112 | return fixer.insertTextBeforeRange(range, "\\");
|
---|
113 | }
|
---|
114 | }
|
---|
115 | ]
|
---|
116 | ]
|
---|
117 | });
|
---|
118 | }
|
---|
119 |
|
---|
120 | /**
|
---|
121 | * Checks if the escape character in given string slice is unnecessary.
|
---|
122 | * @private
|
---|
123 | * @param {ASTNode} node node to validate.
|
---|
124 | * @param {string} match string slice to validate.
|
---|
125 | * @returns {void}
|
---|
126 | */
|
---|
127 | function validateString(node, match) {
|
---|
128 | const isTemplateElement = node.type === "TemplateElement";
|
---|
129 | const escapedChar = match[0][1];
|
---|
130 | let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
|
---|
131 | let isQuoteEscape;
|
---|
132 |
|
---|
133 | if (isTemplateElement) {
|
---|
134 | isQuoteEscape = escapedChar === "`";
|
---|
135 |
|
---|
136 | if (escapedChar === "$") {
|
---|
137 |
|
---|
138 | // Warn if `\$` is not followed by `{`
|
---|
139 | isUnnecessaryEscape = match.input[match.index + 2] !== "{";
|
---|
140 | } else if (escapedChar === "{") {
|
---|
141 |
|
---|
142 | /*
|
---|
143 | * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
|
---|
144 | * is necessary and the rule should not warn. If preceded by `/$`, the rule
|
---|
145 | * will warn for the `/$` instead, as it is the first unnecessarily escaped character.
|
---|
146 | */
|
---|
147 | isUnnecessaryEscape = match.input[match.index - 1] !== "$";
|
---|
148 | }
|
---|
149 | } else {
|
---|
150 | isQuoteEscape = escapedChar === node.raw[0];
|
---|
151 | }
|
---|
152 |
|
---|
153 | if (isUnnecessaryEscape && !isQuoteEscape) {
|
---|
154 | report(node, match.index, match[0].slice(1));
|
---|
155 | }
|
---|
156 | }
|
---|
157 |
|
---|
158 | /**
|
---|
159 | * Checks if the escape character in given regexp is unnecessary.
|
---|
160 | * @private
|
---|
161 | * @param {ASTNode} node node to validate.
|
---|
162 | * @returns {void}
|
---|
163 | */
|
---|
164 | function validateRegExp(node) {
|
---|
165 | const { pattern, flags } = node.regex;
|
---|
166 | let patternNode;
|
---|
167 | const unicode = flags.includes("u");
|
---|
168 | const unicodeSets = flags.includes("v");
|
---|
169 |
|
---|
170 | try {
|
---|
171 | patternNode = parser.parsePattern(pattern, 0, pattern.length, { unicode, unicodeSets });
|
---|
172 | } catch {
|
---|
173 |
|
---|
174 | // Ignore regular expressions with syntax errors
|
---|
175 | return;
|
---|
176 | }
|
---|
177 |
|
---|
178 | /** @type {(CharacterClass | ExpressionCharacterClass)[]} */
|
---|
179 | const characterClassStack = [];
|
---|
180 |
|
---|
181 | visitRegExpAST(patternNode, {
|
---|
182 | onCharacterClassEnter: characterClassNode => characterClassStack.unshift(characterClassNode),
|
---|
183 | onCharacterClassLeave: () => characterClassStack.shift(),
|
---|
184 | onExpressionCharacterClassEnter: characterClassNode => characterClassStack.unshift(characterClassNode),
|
---|
185 | onExpressionCharacterClassLeave: () => characterClassStack.shift(),
|
---|
186 | onCharacterEnter(characterNode) {
|
---|
187 | if (!characterNode.raw.startsWith("\\")) {
|
---|
188 |
|
---|
189 | // It's not an escaped character.
|
---|
190 | return;
|
---|
191 | }
|
---|
192 |
|
---|
193 | const escapedChar = characterNode.raw.slice(1);
|
---|
194 |
|
---|
195 | if (escapedChar !== String.fromCodePoint(characterNode.value)) {
|
---|
196 |
|
---|
197 | // It's a valid escape.
|
---|
198 | return;
|
---|
199 | }
|
---|
200 | let allowedEscapes;
|
---|
201 |
|
---|
202 | if (characterClassStack.length) {
|
---|
203 | allowedEscapes = unicodeSets ? REGEX_CLASSSET_CHARACTER_ESCAPES : REGEX_GENERAL_ESCAPES;
|
---|
204 | } else {
|
---|
205 | allowedEscapes = REGEX_NON_CHARCLASS_ESCAPES;
|
---|
206 | }
|
---|
207 | if (allowedEscapes.has(escapedChar)) {
|
---|
208 | return;
|
---|
209 | }
|
---|
210 |
|
---|
211 | const reportedIndex = characterNode.start + 1;
|
---|
212 | let disableEscapeBackslashSuggest = false;
|
---|
213 |
|
---|
214 | if (characterClassStack.length) {
|
---|
215 | const characterClassNode = characterClassStack[0];
|
---|
216 |
|
---|
217 | if (escapedChar === "^") {
|
---|
218 |
|
---|
219 | /*
|
---|
220 | * The '^' character is also a special case; it must always be escaped outside of character classes, but
|
---|
221 | * it only needs to be escaped in character classes if it's at the beginning of the character class. To
|
---|
222 | * account for this, consider it to be a valid escape character outside of character classes, and filter
|
---|
223 | * out '^' characters that appear at the start of a character class.
|
---|
224 | */
|
---|
225 | if (characterClassNode.start + 1 === characterNode.start) {
|
---|
226 |
|
---|
227 | return;
|
---|
228 | }
|
---|
229 | }
|
---|
230 | if (!unicodeSets) {
|
---|
231 | if (escapedChar === "-") {
|
---|
232 |
|
---|
233 | /*
|
---|
234 | * The '-' character is a special case, because it's only valid to escape it if it's in a character
|
---|
235 | * class, and is not at either edge of the character class. To account for this, don't consider '-'
|
---|
236 | * characters to be valid in general, and filter out '-' characters that appear in the middle of a
|
---|
237 | * character class.
|
---|
238 | */
|
---|
239 | if (characterClassNode.start + 1 !== characterNode.start && characterNode.end !== characterClassNode.end - 1) {
|
---|
240 |
|
---|
241 | return;
|
---|
242 | }
|
---|
243 | }
|
---|
244 | } else { // unicodeSets mode
|
---|
245 | if (REGEX_CLASS_SET_RESERVED_DOUBLE_PUNCTUATOR.has(escapedChar)) {
|
---|
246 |
|
---|
247 | // Escaping is valid if it is a ClassSetReservedDoublePunctuator.
|
---|
248 | if (pattern[characterNode.end] === escapedChar) {
|
---|
249 | return;
|
---|
250 | }
|
---|
251 | if (pattern[characterNode.start - 1] === escapedChar) {
|
---|
252 | if (escapedChar !== "^") {
|
---|
253 | return;
|
---|
254 | }
|
---|
255 |
|
---|
256 | // If the previous character is a `negate` caret(`^`), escape to caret is unnecessary.
|
---|
257 |
|
---|
258 | if (!characterClassNode.negate) {
|
---|
259 | return;
|
---|
260 | }
|
---|
261 | const negateCaretIndex = characterClassNode.start + 1;
|
---|
262 |
|
---|
263 | if (negateCaretIndex < characterNode.start - 1) {
|
---|
264 | return;
|
---|
265 | }
|
---|
266 | }
|
---|
267 | }
|
---|
268 |
|
---|
269 | if (characterNode.parent.type === "ClassIntersection" || characterNode.parent.type === "ClassSubtraction") {
|
---|
270 | disableEscapeBackslashSuggest = true;
|
---|
271 | }
|
---|
272 | }
|
---|
273 | }
|
---|
274 |
|
---|
275 | report(
|
---|
276 | node,
|
---|
277 | reportedIndex,
|
---|
278 | escapedChar,
|
---|
279 | disableEscapeBackslashSuggest
|
---|
280 | );
|
---|
281 | }
|
---|
282 | });
|
---|
283 | }
|
---|
284 |
|
---|
285 | /**
|
---|
286 | * Checks if a node has an escape.
|
---|
287 | * @param {ASTNode} node node to check.
|
---|
288 | * @returns {void}
|
---|
289 | */
|
---|
290 | function check(node) {
|
---|
291 | const isTemplateElement = node.type === "TemplateElement";
|
---|
292 |
|
---|
293 | if (
|
---|
294 | isTemplateElement &&
|
---|
295 | node.parent &&
|
---|
296 | node.parent.parent &&
|
---|
297 | node.parent.parent.type === "TaggedTemplateExpression" &&
|
---|
298 | node.parent === node.parent.parent.quasi
|
---|
299 | ) {
|
---|
300 |
|
---|
301 | // Don't report tagged template literals, because the backslash character is accessible to the tag function.
|
---|
302 | return;
|
---|
303 | }
|
---|
304 |
|
---|
305 | if (typeof node.value === "string" || isTemplateElement) {
|
---|
306 |
|
---|
307 | /*
|
---|
308 | * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
|
---|
309 | * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
|
---|
310 | */
|
---|
311 | if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
|
---|
312 | return;
|
---|
313 | }
|
---|
314 |
|
---|
315 | const value = isTemplateElement ? sourceCode.getText(node) : node.raw;
|
---|
316 | const pattern = /\\[^\d]/gu;
|
---|
317 | let match;
|
---|
318 |
|
---|
319 | while ((match = pattern.exec(value))) {
|
---|
320 | validateString(node, match);
|
---|
321 | }
|
---|
322 | } else if (node.regex) {
|
---|
323 | validateRegExp(node);
|
---|
324 | }
|
---|
325 |
|
---|
326 | }
|
---|
327 |
|
---|
328 | return {
|
---|
329 | Literal: check,
|
---|
330 | TemplateElement: check
|
---|
331 | };
|
---|
332 | }
|
---|
333 | };
|
---|