Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

no-useless-escape.js 8.8KB

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