UNPKG

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