no-useless-escape.js 9.8 KB

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