No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

289 líneas
11 KiB

  1. /**
  2. * @fileoverview A rule to suggest using template literals instead of string concatenation.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Checks whether or not a given node is a concatenation.
  15. * @param {ASTNode} node - A node to check.
  16. * @returns {boolean} `true` if the node is a concatenation.
  17. */
  18. function isConcatenation(node) {
  19. return node.type === "BinaryExpression" && node.operator === "+";
  20. }
  21. /**
  22. * Gets the top binary expression node for concatenation in parents of a given node.
  23. * @param {ASTNode} node - A node to get.
  24. * @returns {ASTNode} the top binary expression node in parents of a given node.
  25. */
  26. function getTopConcatBinaryExpression(node) {
  27. let currentNode = node;
  28. while (isConcatenation(currentNode.parent)) {
  29. currentNode = currentNode.parent;
  30. }
  31. return currentNode;
  32. }
  33. /**
  34. * Determines whether a given node is a octal escape sequence
  35. * @param {ASTNode} node A node to check
  36. * @returns {boolean} `true` if the node is an octal escape sequence
  37. */
  38. function isOctalEscapeSequence(node) {
  39. // No need to check TemplateLiterals – would throw error with octal escape
  40. const isStringLiteral = node.type === "Literal" && typeof node.value === "string";
  41. if (!isStringLiteral) {
  42. return false;
  43. }
  44. const match = node.raw.match(/^([^\\]|\\[^0-7])*\\([0-7]{1,3})/);
  45. if (match) {
  46. // \0 is actually not considered an octal
  47. if (match[2] !== "0" || typeof match[3] !== "undefined") {
  48. return true;
  49. }
  50. }
  51. return false;
  52. }
  53. /**
  54. * Checks whether or not a node contains a octal escape sequence
  55. * @param {ASTNode} node A node to check
  56. * @returns {boolean} `true` if the node contains an octal escape sequence
  57. */
  58. function hasOctalEscapeSequence(node) {
  59. if (isConcatenation(node)) {
  60. return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right);
  61. }
  62. return isOctalEscapeSequence(node);
  63. }
  64. /**
  65. * Checks whether or not a given binary expression has string literals.
  66. * @param {ASTNode} node - A node to check.
  67. * @returns {boolean} `true` if the node has string literals.
  68. */
  69. function hasStringLiteral(node) {
  70. if (isConcatenation(node)) {
  71. // `left` is deeper than `right` normally.
  72. return hasStringLiteral(node.right) || hasStringLiteral(node.left);
  73. }
  74. return astUtils.isStringLiteral(node);
  75. }
  76. /**
  77. * Checks whether or not a given binary expression has non string literals.
  78. * @param {ASTNode} node - A node to check.
  79. * @returns {boolean} `true` if the node has non string literals.
  80. */
  81. function hasNonStringLiteral(node) {
  82. if (isConcatenation(node)) {
  83. // `left` is deeper than `right` normally.
  84. return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
  85. }
  86. return !astUtils.isStringLiteral(node);
  87. }
  88. /**
  89. * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal.
  90. * @param {ASTNode} node The node that will be fixed to a template literal
  91. * @returns {boolean} `true` if the node will start with a template curly.
  92. */
  93. function startsWithTemplateCurly(node) {
  94. if (node.type === "BinaryExpression") {
  95. return startsWithTemplateCurly(node.left);
  96. }
  97. if (node.type === "TemplateLiteral") {
  98. return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1];
  99. }
  100. return node.type !== "Literal" || typeof node.value !== "string";
  101. }
  102. /**
  103. * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal.
  104. * @param {ASTNode} node The node that will be fixed to a template literal
  105. * @returns {boolean} `true` if the node will end with a template curly.
  106. */
  107. function endsWithTemplateCurly(node) {
  108. if (node.type === "BinaryExpression") {
  109. return startsWithTemplateCurly(node.right);
  110. }
  111. if (node.type === "TemplateLiteral") {
  112. return node.expressions.length && node.quasis.length && node.quasis[node.quasis.length - 1].range[0] === node.quasis[node.quasis.length - 1].range[1];
  113. }
  114. return node.type !== "Literal" || typeof node.value !== "string";
  115. }
  116. //------------------------------------------------------------------------------
  117. // Rule Definition
  118. //------------------------------------------------------------------------------
  119. module.exports = {
  120. meta: {
  121. docs: {
  122. description: "require template literals instead of string concatenation",
  123. category: "ECMAScript 6",
  124. recommended: false,
  125. url: "https://eslint.org/docs/rules/prefer-template"
  126. },
  127. schema: [],
  128. fixable: "code"
  129. },
  130. create(context) {
  131. const sourceCode = context.getSourceCode();
  132. let done = Object.create(null);
  133. /**
  134. * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
  135. * @param {ASTNode} node1 The first node
  136. * @param {ASTNode} node2 The second node
  137. * @returns {string} The text between the nodes, excluding other tokens
  138. */
  139. function getTextBetween(node1, node2) {
  140. const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
  141. const sourceText = sourceCode.getText();
  142. return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
  143. }
  144. /**
  145. * Returns a template literal form of the given node.
  146. * @param {ASTNode} currentNode A node that should be converted to a template literal
  147. * @param {string} textBeforeNode Text that should appear before the node
  148. * @param {string} textAfterNode Text that should appear after the node
  149. * @returns {string} A string form of this node, represented as a template literal
  150. */
  151. function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
  152. if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
  153. /*
  154. * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
  155. * as a template placeholder. However, if the code already contains a backslash before the ${ or `
  156. * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
  157. * an actual backslash character to appear before the dollar sign).
  158. */
  159. return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => {
  160. if (matched.lastIndexOf("\\") % 2) {
  161. return `\\${matched}`;
  162. }
  163. return matched;
  164. // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
  165. }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "g"), currentNode.raw[0])}\``;
  166. }
  167. if (currentNode.type === "TemplateLiteral") {
  168. return sourceCode.getText(currentNode);
  169. }
  170. if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
  171. const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
  172. const textBeforePlus = getTextBetween(currentNode.left, plusSign);
  173. const textAfterPlus = getTextBetween(plusSign, currentNode.right);
  174. const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
  175. const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
  176. if (leftEndsWithCurly) {
  177. // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
  178. // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
  179. return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) +
  180. getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
  181. }
  182. if (rightStartsWithCurly) {
  183. // Otherwise, if the right side of the expression starts with a template curly, add the text there.
  184. // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
  185. return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) +
  186. getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
  187. }
  188. /*
  189. * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
  190. * the text between them.
  191. */
  192. return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
  193. }
  194. return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
  195. }
  196. /**
  197. * Returns a fixer object that converts a non-string binary expression to a template literal
  198. * @param {SourceCodeFixer} fixer The fixer object
  199. * @param {ASTNode} node A node that should be converted to a template literal
  200. * @returns {Object} A fix for this binary expression
  201. */
  202. function fixNonStringBinaryExpression(fixer, node) {
  203. const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
  204. if (hasOctalEscapeSequence(topBinaryExpr)) {
  205. return null;
  206. }
  207. return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
  208. }
  209. /**
  210. * Reports if a given node is string concatenation with non string literals.
  211. *
  212. * @param {ASTNode} node - A node to check.
  213. * @returns {void}
  214. */
  215. function checkForStringConcat(node) {
  216. if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
  217. return;
  218. }
  219. const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
  220. // Checks whether or not this node had been checked already.
  221. if (done[topBinaryExpr.range[0]]) {
  222. return;
  223. }
  224. done[topBinaryExpr.range[0]] = true;
  225. if (hasNonStringLiteral(topBinaryExpr)) {
  226. context.report({
  227. node: topBinaryExpr,
  228. message: "Unexpected string concatenation.",
  229. fix: fixer => fixNonStringBinaryExpression(fixer, node)
  230. });
  231. }
  232. }
  233. return {
  234. Program() {
  235. done = Object.create(null);
  236. },
  237. Literal: checkForStringConcat,
  238. TemplateLiteral: checkForStringConcat
  239. };
  240. }
  241. };