项目原始demo,不改动
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

prefer-template.js 9.7 KiB

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