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"
148 unexpectedStringConcatenation
: "Unexpected string concatenation."
153 const sourceCode
= context
.getSourceCode();
154 let done
= Object
.create(null);
157 * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
158 * @param {ASTNode} node1 The first node
159 * @param {ASTNode} node2 The second node
160 * @returns {string} The text between the nodes, excluding other tokens
162 function getTextBetween(node1
, node2
) {
163 const allTokens
= [node1
].concat(sourceCode
.getTokensBetween(node1
, node2
)).concat(node2
);
164 const sourceText
= sourceCode
.getText();
166 return allTokens
.slice(0, -1).reduce((accumulator
, token
, index
) => accumulator
+ sourceText
.slice(token
.range
[1], allTokens
[index
+ 1].range
[0]), "");
170 * Returns a template literal form of the given node.
171 * @param {ASTNode} currentNode A node that should be converted to a template literal
172 * @param {string} textBeforeNode Text that should appear before the node
173 * @param {string} textAfterNode Text that should appear after the node
174 * @returns {string} A string form of this node, represented as a template literal
176 function getTemplateLiteral(currentNode
, textBeforeNode
, textAfterNode
) {
177 if (currentNode
.type
=== "Literal" && typeof currentNode
.value
=== "string") {
180 * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
181 * as a template placeholder. However, if the code already contains a backslash before the ${ or `
182 * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
183 * an actual backslash character to appear before the dollar sign).
185 return `\`${currentNode
.raw
.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched
=> {
186 if (matched
.lastIndexOf("\\") % 2) {
187 return `\\${matched}`;
191 // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
192 }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode
.raw
[0])}\``;
195 if (currentNode
.type
=== "TemplateLiteral") {
196 return sourceCode
.getText(currentNode
);
199 if (isConcatenation(currentNode
) && hasStringLiteral(currentNode
) && hasNonStringLiteral(currentNode
)) {
200 const plusSign
= sourceCode
.getFirstTokenBetween(currentNode
.left
, currentNode
.right
, token
=> token
.value
=== "+");
201 const textBeforePlus
= getTextBetween(currentNode
.left
, plusSign
);
202 const textAfterPlus
= getTextBetween(plusSign
, currentNode
.right
);
203 const leftEndsWithCurly
= endsWithTemplateCurly(currentNode
.left
);
204 const rightStartsWithCurly
= startsWithTemplateCurly(currentNode
.right
);
206 if (leftEndsWithCurly
) {
208 // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
209 // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
210 return getTemplateLiteral(currentNode
.left
, textBeforeNode
, textBeforePlus
+ textAfterPlus
).slice(0, -1) +
211 getTemplateLiteral(currentNode
.right
, null, textAfterNode
).slice(1);
213 if (rightStartsWithCurly
) {
215 // Otherwise, if the right side of the expression starts with a template curly, add the text there.
216 // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
217 return getTemplateLiteral(currentNode
.left
, textBeforeNode
, null).slice(0, -1) +
218 getTemplateLiteral(currentNode
.right
, textBeforePlus
+ textAfterPlus
, textAfterNode
).slice(1);
222 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
223 * the text between them.
225 return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
228 return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}
}\``;
232 * Returns a fixer object that converts a non-string binary expression to a template literal
233 * @param {SourceCodeFixer} fixer The fixer object
234 * @param {ASTNode} node A node that should be converted to a template literal
235 * @returns {Object} A fix for this binary expression
237 function fixNonStringBinaryExpression(fixer
, node
) {
238 const topBinaryExpr
= getTopConcatBinaryExpression(node
.parent
);
240 if (hasOctalEscapeSequence(topBinaryExpr
)) {
244 return fixer
.replaceText(topBinaryExpr
, getTemplateLiteral(topBinaryExpr
, null, null));
248 * Reports if a given node is string concatenation with non string literals.
249 * @param {ASTNode} node A node to check.
252 function checkForStringConcat(node
) {
253 if (!astUtils
.isStringLiteral(node
) || !isConcatenation(node
.parent
)) {
257 const topBinaryExpr
= getTopConcatBinaryExpression(node
.parent
);
259 // Checks whether or not this node had been checked already.
260 if (done
[topBinaryExpr
.range
[0]]) {
263 done
[topBinaryExpr
.range
[0]] = true;
265 if (hasNonStringLiteral(topBinaryExpr
)) {
268 messageId
: "unexpectedStringConcatenation",
269 fix
: fixer
=> fixNonStringBinaryExpression(fixer
, node
)
276 done
= Object
.create(null);
279 Literal
: checkForStringConcat
,
280 TemplateLiteral
: checkForStringConcat