no-useless-escape.js 9.8 KB

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