Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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

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