UNPKG

9.86 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 url: "https://eslint.org/docs/rules/prefer-template"
108 },
109
110 schema: [],
111
112 fixable: "code"
113 },
114
115 create(context) {
116 const sourceCode = context.getSourceCode();
117 let done = Object.create(null);
118
119 /**
120 * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens.
121 * @param {ASTNode} node1 The first node
122 * @param {ASTNode} node2 The second node
123 * @returns {string} The text between the nodes, excluding other tokens
124 */
125 function getTextBetween(node1, node2) {
126 const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2);
127 const sourceText = sourceCode.getText();
128
129 return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), "");
130 }
131
132 /**
133 * Returns a template literal form of the given node.
134 * @param {ASTNode} currentNode A node that should be converted to a template literal
135 * @param {string} textBeforeNode Text that should appear before the node
136 * @param {string} textAfterNode Text that should appear after the node
137 * @returns {string} A string form of this node, represented as a template literal
138 */
139 function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) {
140 if (currentNode.type === "Literal" && typeof currentNode.value === "string") {
141
142 /*
143 * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted
144 * as a template placeholder. However, if the code already contains a backslash before the ${ or `
145 * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause
146 * an actual backslash character to appear before the dollar sign).
147 */
148 return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\${|`)/g, matched => {
149 if (matched.lastIndexOf("\\") % 2) {
150 return `\\${matched}`;
151 }
152 return matched;
153
154 // Unescape any quotes that appear in the original Literal that no longer need to be escaped.
155 }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "g"), currentNode.raw[0])}\``;
156 }
157
158 if (currentNode.type === "TemplateLiteral") {
159 return sourceCode.getText(currentNode);
160 }
161
162 if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) {
163 const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+");
164 const textBeforePlus = getTextBetween(currentNode.left, plusSign);
165 const textAfterPlus = getTextBetween(plusSign, currentNode.right);
166 const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left);
167 const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right);
168
169 if (leftEndsWithCurly) {
170
171 // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket.
172 // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}`
173 return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) +
174 getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1);
175 }
176 if (rightStartsWithCurly) {
177
178 // Otherwise, if the right side of the expression starts with a template curly, add the text there.
179 // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz`
180 return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) +
181 getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1);
182 }
183
184 /*
185 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put
186 * the text between them.
187 */
188 return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`;
189 }
190
191 return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``;
192 }
193
194 /**
195 * Reports if a given node is string concatenation with non string literals.
196 *
197 * @param {ASTNode} node - A node to check.
198 * @returns {void}
199 */
200 function checkForStringConcat(node) {
201 if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) {
202 return;
203 }
204
205 const topBinaryExpr = getTopConcatBinaryExpression(node.parent);
206
207 // Checks whether or not this node had been checked already.
208 if (done[topBinaryExpr.range[0]]) {
209 return;
210 }
211 done[topBinaryExpr.range[0]] = true;
212
213 if (hasNonStringLiteral(topBinaryExpr)) {
214 context.report({
215 node: topBinaryExpr,
216 message: "Unexpected string concatenation.",
217 fix(fixer) {
218 return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null));
219 }
220 });
221 }
222 }
223
224 return {
225 Program() {
226 done = Object.create(null);
227 },
228
229 Literal: checkForStringConcat,
230 TemplateLiteral: checkForStringConcat
231 };
232 }
233};