UNPKG

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