UNPKG

11.5 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("./utils/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 return astUtils.hasOctalEscapeSequence(node.raw);
56}
57
58/**
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
62 */
63function hasOctalEscapeSequence(node) {
64 if (isConcatenation(node)) {
65 return hasOctalEscapeSequence(node.left) || hasOctalEscapeSequence(node.right);
66 }
67
68 return isOctalEscapeSequence(node);
69}
70
71/**
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.
75 */
76function hasStringLiteral(node) {
77 if (isConcatenation(node)) {
78
79 // `left` is deeper than `right` normally.
80 return hasStringLiteral(node.right) || hasStringLiteral(node.left);
81 }
82 return astUtils.isStringLiteral(node);
83}
84
85/**
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.
89 */
90function hasNonStringLiteral(node) {
91 if (isConcatenation(node)) {
92
93 // `left` is deeper than `right` normally.
94 return hasNonStringLiteral(node.right) || hasNonStringLiteral(node.left);
95 }
96 return !astUtils.isStringLiteral(node);
97}
98
99/**
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.
103 */
104function startsWithTemplateCurly(node) {
105 if (node.type === "BinaryExpression") {
106 return startsWithTemplateCurly(node.left);
107 }
108 if (node.type === "TemplateLiteral") {
109 return node.expressions.length && node.quasis.length && node.quasis[0].range[0] === node.quasis[0].range[1];
110 }
111 return node.type !== "Literal" || typeof node.value !== "string";
112}
113
114/**
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.
118 */
119function endsWithTemplateCurly(node) {
120 if (node.type === "BinaryExpression") {
121 return startsWithTemplateCurly(node.right);
122 }
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];
125 }
126 return node.type !== "Literal" || typeof node.value !== "string";
127}
128
129//------------------------------------------------------------------------------
130// Rule Definition
131//------------------------------------------------------------------------------
132
133module.exports = {
134 meta: {
135 type: "suggestion",
136
137 docs: {
138 description: "require template literals instead of string concatenation",
139 category: "ECMAScript 6",
140 recommended: false,
141 url: "https://eslint.org/docs/rules/prefer-template"
142 },
143
144 schema: [],
145 fixable: "code"
146 },
147
148 create(context) {
149 const sourceCode = context.getSourceCode();
150 let done = Object.create(null);
151
152 /**
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
157 */
158 function getTextBetween(node1, node2) {
159 const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
160 const sourceText = sourceCode.getText();
161
162 return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
163 }
164
165 /**
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
171 */
172 function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
173 if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
174
175 /*
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).
180 */
181 return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => {
182 if (matched.lastIndexOf("\\") % 2) {
183 return `\\${matched}`;
184 }
185 return matched;
186
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])}\``;
189 }
190
191 if (currentNode.type === "TemplateLiteral") {
192 return sourceCode.getText(currentNode);
193 }
194
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);
201
202 if (leftEndsWithCurly) {
203
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);
208 }
209 if (rightStartsWithCurly) {
210
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);
215 }
216
217 /*
218 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
219 * the text between them.
220 */
221 return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
222 }
223
224 return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
225 }
226
227 /**
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
232 */
233 function fixNonStringBinaryExpression(fixer, node) {
234 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
235
236 if (hasOctalEscapeSequence(topBinaryExpr)) {
237 return null;
238 }
239
240 return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
241 }
242
243 /**
244 * Reports if a given node is string concatenation with non string literals.
245 *
246 * @param {ASTNode} node - A node to check.
247 * @returns {void}
248 */
249 function checkForStringConcat(node) {
250 if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
251 return;
252 }
253
254 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
255
256 // Checks whether or not this node had been checked already.
257 if (done[topBinaryExpr.range[0]]) {
258 return;
259 }
260 done[topBinaryExpr.range[0]] = true;
261
262 if (hasNonStringLiteral(topBinaryExpr)) {
263 context.report({
264 node: topBinaryExpr,
265 message: "Unexpected string concatenation.",
266 fix: fixer => fixNonStringBinaryExpression(fixer, node)
267 });
268 }
269 }
270
271 return {
272 Program() {
273 done = Object.create(null);
274 },
275
276 Literal: checkForStringConcat,
277 TemplateLiteral: checkForStringConcat
278 };
279 }
280};