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