2 * @fileoverview A rule to suggest using template literals instead of string concatenation.
3 * @author Toru Nagashima
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
19 * Checks whether or not a given node is a concatenation.
20 * @param {ASTNode} node A node to check.
21 * @returns {boolean} `true` if the node is a concatenation.
23 function isConcatenation(node) {
24 return node.type === "BinaryExpression" && node.operator === "+";
28 * Gets the top binary expression node for concatenation in parents of a given node.
29 * @param {ASTNode} node A node to get.
30 * @returns {ASTNode} the top binary expression node in parents of a given node.
32 function getTopConcatBinaryExpression(node) {
33 let currentNode = node;
35 while (isConcatenation(currentNode.parent)) {
36 currentNode = currentNode.parent;
42 * Determines whether a given node is a octal escape sequence
43 * @param {ASTNode} node A node to check
44 * @returns {boolean} `true` if the node is an octal escape sequence
46 function isOctalEscapeSequence(node) {
48 // No need to check TemplateLiterals – would throw error with octal escape
49 const isStringLiteral = node.type === "Literal" && typeof node.value === "string";
51 if (!isStringLiteral) {
55 return astUtils.hasOctalEscapeSequence(node.raw);
59 * Checks whether or not a node contains a octal escape sequence
60 * @param {ASTNode} node A node to check
61 * @returns {boolean} `true` if the node contains an octal escape sequence
63 function hasOctalEscapeSequence(node) {
64 if (isConcatenation(node)) {
65 return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right);
68 return isOctalEscapeSequence(node);
72 * Checks whether or not a given binary expression has string literals.
73 * @param {ASTNode} node A node to check.
74 * @returns {boolean} `true` if the node has string literals.
76 function hasStringLiteral(node) {
77 if (isConcatenation(node)) {
79 // `left` is deeper than `right` normally.
80 return hasStringLiteral(node.right) || hasStringLiteral(node.left);
82 return astUtils.isStringLiteral(node);
86 * Checks whether or not a given binary expression has non string literals.
87 * @param {ASTNode} node A node to check.
88 * @returns {boolean} `true` if the node has non string literals.
90 function hasNonStringLiteral(node) {
91 if (isConcatenation(node)) {
93 // `left` is deeper than `right` normally.
94 return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
96 return !astUtils.isStringLiteral(node);
100 * Determines whether a given node will start with a template curly expression (`${}`) when being converted to a template literal.
101 * @param {ASTNode} node The node that will be fixed to a template literal
102 * @returns {boolean} `true` if the node will start with a template curly.
104 function startsWithTemplateCurly(node) {
105 if (node.type === "BinaryExpression") {
106 return startsWithTemplateCurly(node.left);
108 if (node.type === "TemplateLiteral") {
109 return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1];
111 return node.type !== "Literal" || typeof node.value !== "string";
115 * Determines whether a given node end with a template curly expression (`${}`) when being converted to a template literal.
116 * @param {ASTNode} node The node that will be fixed to a template literal
117 * @returns {boolean} `true` if the node will end with a template curly.
119 function endsWithTemplateCurly(node) {
120 if (node.type === "BinaryExpression") {
121 return startsWithTemplateCurly(node.right);
123 if (node.type === "TemplateLiteral") {
124 return node.expressions.length && node.quasis.length && node.quasis[node.quasis.length - 1].range[0] === node.quasis[node.quasis.length - 1].range[1];
126 return node.type !== "Literal" || typeof node.value !== "string";
129 //------------------------------------------------------------------------------
131 //------------------------------------------------------------------------------
138 description: "require template literals instead of string concatenation",
139 category: "ECMAScript 6",
141 url: "https://eslint.org/docs/rules/prefer-template"
149 const sourceCode = context.getSourceCode();
150 let done = Object.create(null);
153 * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
154 * @param {ASTNode} node1 The first node
155 * @param {ASTNode} node2 The second node
156 * @returns {string} The text between the nodes, excluding other tokens
158 function getTextBetween(node1, node2) {
159 const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
160 const sourceText = sourceCode.getText();
162 return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
166 * Returns a template literal form of the given node.
167 * @param {ASTNode} currentNode A node that should be converted to a template literal
168 * @param {string} textBeforeNode Text that should appear before the node
169 * @param {string} textAfterNode Text that should appear after the node
170 * @returns {string} A string form of this node, represented as a template literal
172 function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
173 if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
176 * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
177 * as a template placeholder. However, if the code already contains a backslash before the ${ or `
178 * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
179 * an actual backslash character to appear before the dollar sign).
181 return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => {
182 if (matched.lastIndexOf("\\") % 2) {
183 return `\\${matched}`;
187 // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
188 }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``;
191 if (currentNode.type === "TemplateLiteral") {
192 return sourceCode.getText(currentNode);
195 if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
196 const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
197 const textBeforePlus = getTextBetween(currentNode.left, plusSign);
198 const textAfterPlus = getTextBetween(plusSign, currentNode.right);
199 const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
200 const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
202 if (leftEndsWithCurly) {
204 // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
205 // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
206 return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) +
207 getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
209 if (rightStartsWithCurly) {
211 // Otherwise, if the right side of the expression starts with a template curly, add the text there.
212 // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
213 return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) +
214 getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
218 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
219 * the text between them.
221 return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
224 return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
228 * Returns a fixer object that converts a non-string binary expression to a template literal
229 * @param {SourceCodeFixer} fixer The fixer object
230 * @param {ASTNode} node A node that should be converted to a template literal
231 * @returns {Object} A fix for this binary expression
233 function fixNonStringBinaryExpression(fixer, node) {
234 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
236 if (hasOctalEscapeSequence(topBinaryExpr)) {
240 return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
244 * Reports if a given node is string concatenation with non string literals.
245 * @param {ASTNode} node A node to check.
248 function checkForStringConcat(node) {
249 if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
253 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
255 // Checks whether or not this node had been checked already.
256 if (done[topBinaryExpr.range[0]]) {
259 done[topBinaryExpr.range[0]] = true;
261 if (hasNonStringLiteral(topBinaryExpr)) {
264 message: "Unexpected string concatenation.",
265 fix: fixer => fixNonStringBinaryExpression(fixer, node)
272 done = Object.create(null);
275 Literal: checkForStringConcat,
276 TemplateLiteral: checkForStringConcat