项目原始demo,不改动
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
このリポジトリはアーカイブされています。 ファイルの閲覧とクローンは可能ですが、プッシュや、課題・プルリクエストのオープンはできません。
 
 
 
 

225 行
8.8 KiB

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