1 | /**
|
2 | * @fileoverview Look for useless escapes in strings and regexes
|
3 | * @author Onur Temizkan
|
4 | */
|
5 |
|
6 | ;
|
7 |
|
8 | const astUtils = require("../util/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 | function parseRegExp(regExpText) {
|
49 | const charList = [];
|
50 |
|
51 | regExpText.split("").reduce((state, char, index) => {
|
52 | if (!state.escapeNextChar) {
|
53 | if (char === "\\") {
|
54 | return Object.assign(state, { escapeNextChar: true });
|
55 | }
|
56 | if (char === "[" && !state.inCharClass) {
|
57 | return Object.assign(state, { inCharClass: true, startingCharClass: true });
|
58 | }
|
59 | if (char === "]" && state.inCharClass) {
|
60 | if (charList.length && charList[charList.length - 1].inCharClass) {
|
61 | charList[charList.length - 1].endsCharClass = true;
|
62 | }
|
63 | return Object.assign(state, { inCharClass: false, startingCharClass: false });
|
64 | }
|
65 | }
|
66 | charList.push({
|
67 | text: char,
|
68 | index,
|
69 | escaped: state.escapeNextChar,
|
70 | inCharClass: state.inCharClass,
|
71 | startsCharClass: state.startingCharClass,
|
72 | endsCharClass: false
|
73 | });
|
74 | return Object.assign(state, { escapeNextChar: false, startingCharClass: false });
|
75 | }, { escapeNextChar: false, inCharClass: false, startingCharClass: false });
|
76 |
|
77 | return charList;
|
78 | }
|
79 |
|
80 | module.exports = {
|
81 | meta: {
|
82 | type: "suggestion",
|
83 |
|
84 | docs: {
|
85 | description: "disallow unnecessary escape characters",
|
86 | category: "Best Practices",
|
87 | recommended: true,
|
88 | url: "https://eslint.org/docs/rules/no-useless-escape"
|
89 | },
|
90 |
|
91 | schema: []
|
92 | },
|
93 |
|
94 | create(context) {
|
95 | const sourceCode = context.getSourceCode();
|
96 |
|
97 | /**
|
98 | * Reports a node
|
99 | * @param {ASTNode} node The node to report
|
100 | * @param {number} startOffset The backslash's offset from the start of the node
|
101 | * @param {string} character The uselessly escaped character (not including the backslash)
|
102 | * @returns {void}
|
103 | */
|
104 | function report(node, startOffset, character) {
|
105 | context.report({
|
106 | node,
|
107 | loc: sourceCode.getLocFromIndex(sourceCode.getIndexFromLoc(node.loc.start) + startOffset),
|
108 | message: "Unnecessary escape character: \\{{character}}.",
|
109 | data: { character }
|
110 | });
|
111 | }
|
112 |
|
113 | /**
|
114 | * Checks if the escape character in given string slice is unnecessary.
|
115 | *
|
116 | * @private
|
117 | * @param {ASTNode} node - node to validate.
|
118 | * @param {string} match - string slice to validate.
|
119 | * @returns {void}
|
120 | */
|
121 | function validateString(node, match) {
|
122 | const isTemplateElement = node.type === "TemplateElement";
|
123 | const escapedChar = match[0][1];
|
124 | let isUnnecessaryEscape = !VALID_STRING_ESCAPES.has(escapedChar);
|
125 | let isQuoteEscape;
|
126 |
|
127 | if (isTemplateElement) {
|
128 | isQuoteEscape = escapedChar === "`";
|
129 |
|
130 | if (escapedChar === "$") {
|
131 |
|
132 | // Warn if `\$` is not followed by `{`
|
133 | isUnnecessaryEscape = match.input[match.index + 2] !== "{";
|
134 | } else if (escapedChar === "{") {
|
135 |
|
136 | /*
|
137 | * Warn if `\{` is not preceded by `$`. If preceded by `$`, escaping
|
138 | * is necessary and the rule should not warn. If preceded by `/$`, the rule
|
139 | * will warn for the `/$` instead, as it is the first unnecessarily escaped character.
|
140 | */
|
141 | isUnnecessaryEscape = match.input[match.index - 1] !== "$";
|
142 | }
|
143 | } else {
|
144 | isQuoteEscape = escapedChar === node.raw[0];
|
145 | }
|
146 |
|
147 | if (isUnnecessaryEscape && !isQuoteEscape) {
|
148 | report(node, match.index + 1, match[0].slice(1));
|
149 | }
|
150 | }
|
151 |
|
152 | /**
|
153 | * Checks if a node has an escape.
|
154 | *
|
155 | * @param {ASTNode} node - node to check.
|
156 | * @returns {void}
|
157 | */
|
158 | function check(node) {
|
159 | const isTemplateElement = node.type === "TemplateElement";
|
160 |
|
161 | if (
|
162 | isTemplateElement &&
|
163 | node.parent &&
|
164 | node.parent.parent &&
|
165 | node.parent.parent.type === "TaggedTemplateExpression" &&
|
166 | node.parent === node.parent.parent.quasi
|
167 | ) {
|
168 |
|
169 | // Don't report tagged template literals, because the backslash character is accessible to the tag function.
|
170 | return;
|
171 | }
|
172 |
|
173 | if (typeof node.value === "string" || isTemplateElement) {
|
174 |
|
175 | /*
|
176 | * JSXAttribute doesn't have any escape sequence: https://facebook.github.io/jsx/.
|
177 | * In addition, backticks are not supported by JSX yet: https://github.com/facebook/jsx/issues/25.
|
178 | */
|
179 | if (node.parent.type === "JSXAttribute" || node.parent.type === "JSXElement" || node.parent.type === "JSXFragment") {
|
180 | return;
|
181 | }
|
182 |
|
183 | const value = isTemplateElement ? node.value.raw : node.raw.slice(1, -1);
|
184 | const pattern = /\\[^\d]/gu;
|
185 | let match;
|
186 |
|
187 | while ((match = pattern.exec(value))) {
|
188 | validateString(node, match);
|
189 | }
|
190 | } else if (node.regex) {
|
191 | parseRegExp(node.regex.pattern)
|
192 |
|
193 | /*
|
194 | * The '-' character is a special case, because it's only valid to escape it if it's in a character
|
195 | * class, and is not at either edge of the character class. To account for this, don't consider '-'
|
196 | * characters to be valid in general, and filter out '-' characters that appear in the middle of a
|
197 | * character class.
|
198 | */
|
199 | .filter(charInfo => !(charInfo.text === "-" && charInfo.inCharClass && !charInfo.startsCharClass && !charInfo.endsCharClass))
|
200 |
|
201 | /*
|
202 | * The '^' character is also a special case; it must always be escaped outside of character classes, but
|
203 | * it only needs to be escaped in character classes if it's at the beginning of the character class. To
|
204 | * account for this, consider it to be a valid escape character outside of character classes, and filter
|
205 | * out '^' characters that appear at the start of a character class.
|
206 | */
|
207 | .filter(charInfo => !(charInfo.text === "^" && charInfo.startsCharClass))
|
208 |
|
209 | // Filter out characters that aren't escaped.
|
210 | .filter(charInfo => charInfo.escaped)
|
211 |
|
212 | // Filter out characters that are valid to escape, based on their position in the regular expression.
|
213 | .filter(charInfo => !(charInfo.inCharClass ? REGEX_GENERAL_ESCAPES : REGEX_NON_CHARCLASS_ESCAPES).has(charInfo.text))
|
214 |
|
215 | // Report all the remaining characters.
|
216 | .forEach(charInfo => report(node, charInfo.index, charInfo.text));
|
217 | }
|
218 |
|
219 | }
|
220 |
|
221 | return {
|
222 | Literal: check,
|
223 | TemplateElement: check
|
224 | };
|
225 | }
|
226 | };
|