UNPKG

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