prefer-template.js 11 KB

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