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.

prefer-template.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. type: "suggestion",
  122. docs: {
  123. description: "require template literals instead of string concatenation",
  124. category: "ECMAScript 6",
  125. recommended: false,
  126. url: "https://eslint.org/docs/rules/prefer-template"
  127. },
  128. schema: [],
  129. fixable: "code"
  130. },
  131. create(context) {
  132. const sourceCode = context.getSourceCode();
  133. let done = Object.create(null);
  134. /**
  135. * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
  136. * @param {ASTNode} node1 The first node
  137. * @param {ASTNode} node2 The second node
  138. * @returns {string} The text between the nodes, excluding other tokens
  139. */
  140. function getTextBetween(node1, node2) {
  141. const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
  142. const sourceText = sourceCode.getText();
  143. return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
  144. }
  145. /**
  146. * Returns a template literal form of the given node.
  147. * @param {ASTNode} currentNode A node that should be converted to a template literal
  148. * @param {string} textBeforeNode Text that should appear before the node
  149. * @param {string} textAfterNode Text that should appear after the node
  150. * @returns {string} A string form of this node, represented as a template literal
  151. */
  152. function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
  153. if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
  154. /*
  155. * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
  156. * as a template placeholder. However, if the code already contains a backslash before the ${ or `
  157. * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
  158. * an actual backslash character to appear before the dollar sign).
  159. */
  160. return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => {
  161. if (matched.lastIndexOf("\\") % 2) {
  162. return `\\${matched}`;
  163. }
  164. return matched;
  165. // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
  166. }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "g"), currentNode.raw[0])}\``;
  167. }
  168. if (currentNode.type === "TemplateLiteral") {
  169. return sourceCode.getText(currentNode);
  170. }
  171. if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
  172. const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
  173. const textBeforePlus = getTextBetween(currentNode.left, plusSign);
  174. const textAfterPlus = getTextBetween(plusSign, currentNode.right);
  175. const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
  176. const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
  177. if (leftEndsWithCurly) {
  178. // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
  179. // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
  180. return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) +
  181. getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
  182. }
  183. if (rightStartsWithCurly) {
  184. // Otherwise, if the right side of the expression starts with a template curly, add the text there.
  185. // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
  186. return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) +
  187. getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
  188. }
  189. /*
  190. * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
  191. * the text between them.
  192. */
  193. return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
  194. }
  195. return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
  196. }
  197. /**
  198. * Returns a fixer object that converts a non-string binary expression to a template literal
  199. * @param {SourceCodeFixer} fixer The fixer object
  200. * @param {ASTNode} node A node that should be converted to a template literal
  201. * @returns {Object} A fix for this binary expression
  202. */
  203. function fixNonStringBinaryExpression(fixer, node) {
  204. const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
  205. if (hasOctalEscapeSequence(topBinaryExpr)) {
  206. return null;
  207. }
  208. return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
  209. }
  210. /**
  211. * Reports if a given node is string concatenation with non string literals.
  212. *
  213. * @param {ASTNode} node - A node to check.
  214. * @returns {void}
  215. */
  216. function checkForStringConcat(node) {
  217. if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
  218. return;
  219. }
  220. const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
  221. // Checks whether or not this node had been checked already.
  222. if (done[topBinaryExpr.range[0]]) {
  223. return;
  224. }
  225. done[topBinaryExpr.range[0]] = true;
  226. if (hasNonStringLiteral(topBinaryExpr)) {
  227. context.report({
  228. node: topBinaryExpr,
  229. message: "Unexpected string concatenation.",
  230. fix: fixer => fixNonStringBinaryExpression(fixer, node)
  231. });
  232. }
  233. }
  234. return {
  235. Program() {
  236. done = Object.create(null);
  237. },
  238. Literal: checkForStringConcat,
  239. TemplateLiteral: checkForStringConcat
  240. };
  241. }
  242. };