]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-useless-escape.js
change from CLIEngine to ESLint
[pve-eslint.git] / eslint / lib / rules / no-useless-escape.js
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
10 //------------------------------------------------------------------------------
11 // Rule Definition
12 //------------------------------------------------------------------------------
13
14 /**
15 * Returns the union of two sets.
16 * @param {Set} setA The first set
17 * @param {Set} setB The second set
18 * @returns {Set} The union of the two sets
19 */
20 function union(setA, setB) {
21 return new Set(function *() {
22 yield* setA;
23 yield* setB;
24 }());
25 }
26
27 const VALID_STRING_ESCAPES = union(new Set("\\nrvtbfux"), astUtils.LINEBREAKS);
28 const REGEX_GENERAL_ESCAPES = new Set("\\bcdDfnpPrsStvwWxu0123456789]");
29 const REGEX_NON_CHARCLASS_ESCAPES = union(REGEX_GENERAL_ESCAPES, new Set("^/.$*+?[{}|()Bk"));
30
31 /**
32 * Parses a regular expression into a list of characters with character class info.
33 * @param {string} regExpText The raw text used to create the regular expression
34 * @returns {Object[]} A list of characters, each with info on escaping and whether they're in a character class.
35 * @example
36 *
37 * parseRegExp("a\\b[cd-]");
38 *
39 * // returns:
40 * [
41 * { text: "a", index: 0, escaped: false, inCharClass: false, startsCharClass: false, endsCharClass: false },
42 * { text: "b", index: 2, escaped: true, inCharClass: false, startsCharClass: false, endsCharClass: false },
43 * { text: "c", index: 4, escaped: false, inCharClass: true, startsCharClass: true, endsCharClass: false },
44 * { text: "d", index: 5, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false },
45 * { text: "-", index: 6, escaped: false, inCharClass: true, startsCharClass: false, endsCharClass: false }
46 * ];
47 *
48 */
49 function parseRegExp(regExpText) {
50 const charList = [];
51
52 regExpText.split("").reduce((state, char, index) => {
53 if (!state.escapeNextChar) {
54 if (char === "\\") {
55 return Object.assign(state, { escapeNextChar: true });
56 }
57 if (char === "[" && !state.inCharClass) {
58 return Object.assign(state, { inCharClass: true, startingCharClass: true });
59 }
60 if (char === "]" && state.inCharClass) {
61 if (charList.length && charList[charList.length - 1].inCharClass) {
62 charList[charList.length - 1].endsCharClass = true;
63 }
64 return Object.assign(state, { inCharClass: false, startingCharClass: false });
65 }
66 }
67 charList.push({
68 text: char,
69 index,
70 escaped: state.escapeNextChar,
71 inCharClass: state.inCharClass,
72 startsCharClass: state.startingCharClass,
73 endsCharClass: false
74 });
75 return Object.assign(state, { escapeNextChar: false, startingCharClass: false });
76 }, { escapeNextChar: false, inCharClass: false, startingCharClass: false });
77
78 return charList;
79 }
80
81 module.exports = {
82 meta: {
83 type: "suggestion",
84
85 docs: {
86 description: "disallow unnecessary escape characters",
87 recommended: true,
88 url: "https://eslint.org/docs/rules/no-useless-escape"
89 },
90
91 hasSuggestions: true,
92
93 messages: {
94 unnecessaryEscape: "Unnecessary escape character: \\{{character}}.",
95 removeEscape: "Remove the `\\`. This maintains the current functionality.",
96 escapeBackslash: "Replace the `\\` with `\\\\` to include the actual backslash character."
97 },
98
99 schema: []
100 },
101
102 create(context) {
103 const sourceCode = context.getSourceCode();
104
105 /**
106 * Reports a node
107 * @param {ASTNode} node The node to report
108 * @param {number} startOffset The backslash's offset from the start of the node
109 * @param {string} character The uselessly escaped character (not including the backslash)
110 * @returns {void}
111 */
112 function report(node, startOffset, character) {
113 const rangeStart = node.range[0] + startOffset;
114 const range = [rangeStart, rangeStart + 1];
115 const start = sourceCode.getLocFromIndex(rangeStart);
116
117 context.report({
118 node,
119 loc: {
120 start,
121 end: { line: start.line, column: start.column + 1 }
122 },
123 messageId: "unnecessaryEscape",
124 data: { character },
125 suggest: [
126 {
127 messageId: "removeEscape",
128 fix(fixer) {
129 return fixer.removeRange(range);
130 }
131 },
132 {
133 messageId: "escapeBackslash",
134 fix(fixer) {
135 return fixer.insertTextBeforeRange(range, "\\");
136 }
137 }
138 ]
139 });
140 }
141
142 /**
143 * Checks if the escape character in given string slice is unnecessary.
144 * @private
145 * @param {ASTNode} node node to validate.
146 * @param {string} match string slice to validate.
147 * @returns {void}
148 */
149 function validateString(node, match) {
150 const isTemplateElement = node.type === "TemplateElement";
151 const escapedChar = match[0][1];
152 let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
153 let isQuoteEscape;
154
155 if (isTemplateElement) {
156 isQuoteEscape = escapedChar === "`";
157
158 if (escapedChar === "$") {
159
160 // Warn if `\$` is not followed by `{`
161 isUnnecessaryEscape = match.input[match.index + 2] !== "{";
162 } else if (escapedChar === "{") {
163
164 /*
165 * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
166 * is necessary and the rule should not warn. If preceded by `/$`, the rule
167 * will warn for the `/$` instead, as it is the first unnecessarily escaped character.
168 */
169 isUnnecessaryEscape = match.input[match.index - 1] !== "$";
170 }
171 } else {
172 isQuoteEscape = escapedChar === node.raw[0];
173 }
174
175 if (isUnnecessaryEscape && !isQuoteEscape) {
176 report(node, match.index, match[0].slice(1));
177 }
178 }
179
180 /**
181 * Checks if a node has an escape.
182 * @param {ASTNode} node node to check.
183 * @returns {void}
184 */
185 function check(node) {
186 const isTemplateElement = node.type === "TemplateElement";
187
188 if (
189 isTemplateElement &&
190 node.parent &&
191 node.parent.parent &&
192 node.parent.parent.type === "TaggedTemplateExpression" &&
193 node.parent === node.parent.parent.quasi
194 ) {
195
196 // Don't report tagged template literals, because the backslash character is accessible to the tag function.
197 return;
198 }
199
200 if (typeof node.value === "string" || isTemplateElement) {
201
202 /*
203 * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
204 * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
205 */
206 if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
207 return;
208 }
209
210 const value = isTemplateElement ? sourceCode.getText(node) : node.raw;
211 const pattern = /\\[^\d]/gu;
212 let match;
213
214 while ((match = pattern.exec(value))) {
215 validateString(node, match);
216 }
217 } else if (node.regex) {
218 parseRegExp(node.regex.pattern)
219
220 /*
221 * The '-' character is a special case, because it's only valid to escape it if it's in a character
222 * class, and is not at either edge of the character class. To account for this, don't consider '-'
223 * characters to be valid in general, and filter out '-' characters that appear in the middle of a
224 * character class.
225 */
226 .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
227
228 /*
229 * The '^' character is also a special case; it must always be escaped outside of character classes, but
230 * it only needs to be escaped in character classes if it's at the beginning of the character class. To
231 * account for this, consider it to be a valid escape character outside of character classes, and filter
232 * out '^' characters that appear at the start of a character class.
233 */
234 .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass))
235
236 // Filter out characters that aren't escaped.
237 .filter(charInfo => charInfo.escaped)
238
239 // Filter out characters that are valid to escape, based on their position in the regular expression.
240 .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text))
241
242 // Report all the remaining characters.
243 .forEach(charInfo => report(node, charInfo.index, charInfo.text));
244 }
245
246 }
247
248 return {
249 Literal: check,
250 TemplateElement: check
251 };
252 }
253 };