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 messages: { 148 unexpectedStringConcatenation: "Unexpected string concatenation." 149 } 150 }, 151 152 create(context) { 153 const sourceCode = context.getSourceCode(); 154 let done = Object.create(null); 155 156 /** 157 * Gets the non-token text between two nodes, ignoring any other tokens that appear between the two tokens. 158 * @param {ASTNode} node1 The first node 159 * @param {ASTNode} node2 The second node 160 * @returns {string} The text between the nodes, excluding other tokens 161 */ 162 function getTextBetween(node1, node2) { 163 const allTokens = [node1].concat(sourceCode.getTokensBetween(node1, node2)).concat(node2); 164 const sourceText = sourceCode.getText(); 165 166 return allTokens.slice(0, -1).reduce((accumulator, token, index) => accumulator + sourceText.slice(token.range[1], allTokens[index + 1].range[0]), ""); 167 } 168 169 /** 170 * Returns a template literal form of the given node. 171 * @param {ASTNode} currentNode A node that should be converted to a template literal 172 * @param {string} textBeforeNode Text that should appear before the node 173 * @param {string} textAfterNode Text that should appear after the node 174 * @returns {string} A string form of this node, represented as a template literal 175 */ 176 function getTemplateLiteral(currentNode, textBeforeNode, textAfterNode) { 177 if (currentNode.type === "Literal" && typeof currentNode.value === "string") { 178 179 /* 180 * If the current node is a string literal, escape any instances of ${ or ` to prevent them from being interpreted 181 * as a template placeholder. However, if the code already contains a backslash before the ${ or ` 182 * for some reason, don't add another backslash, because that would change the meaning of the code (it would cause 183 * an actual backslash character to appear before the dollar sign). 184 */ 185 return `\`${currentNode.raw.slice(1, -1).replace(/\\*(\$\{|`)/gu, matched => { 186 if (matched.lastIndexOf("\\") % 2) { 187 return `\\${matched}`; 188 } 189 return matched; 190 191 // Unescape any quotes that appear in the original Literal that no longer need to be escaped. 192 }).replace(new RegExp(`\\\\${currentNode.raw[0]}`, "gu"), currentNode.raw[0])}\``; 193 } 194 195 if (currentNode.type === "TemplateLiteral") { 196 return sourceCode.getText(currentNode); 197 } 198 199 if (isConcatenation(currentNode) && hasStringLiteral(currentNode) && hasNonStringLiteral(currentNode)) { 200 const plusSign = sourceCode.getFirstTokenBetween(currentNode.left, currentNode.right, token => token.value === "+"); 201 const textBeforePlus = getTextBetween(currentNode.left, plusSign); 202 const textAfterPlus = getTextBetween(plusSign, currentNode.right); 203 const leftEndsWithCurly = endsWithTemplateCurly(currentNode.left); 204 const rightStartsWithCurly = startsWithTemplateCurly(currentNode.right); 205 206 if (leftEndsWithCurly) { 207 208 // If the left side of the expression ends with a template curly, add the extra text to the end of the curly bracket. 209 // `foo${bar}` /* comment */ + 'baz' --> `foo${bar /* comment */ }${baz}` 210 return getTemplateLiteral(currentNode.left, textBeforeNode, textBeforePlus + textAfterPlus).slice(0, -1) + 211 getTemplateLiteral(currentNode.right, null, textAfterNode).slice(1); 212 } 213 if (rightStartsWithCurly) { 214 215 // Otherwise, if the right side of the expression starts with a template curly, add the text there. 216 // 'foo' /* comment */ + `${bar}baz` --> `foo${ /* comment */ bar}baz` 217 return getTemplateLiteral(currentNode.left, textBeforeNode, null).slice(0, -1) + 218 getTemplateLiteral(currentNode.right, textBeforePlus + textAfterPlus, textAfterNode).slice(1); 219 } 220 221 /* 222 * Otherwise, these nodes should not be combined into a template curly, since there is nowhere to put 223 * the text between them. 224 */ 225 return `${getTemplateLiteral(currentNode.left, textBeforeNode, null)}${textBeforePlus}+${textAfterPlus}${getTemplateLiteral(currentNode.right, textAfterNode, null)}`; 226 } 227 228 return `\`\${${textBeforeNode || ""}${sourceCode.getText(currentNode)}${textAfterNode || ""}}\``; 229 } 230 231 /** 232 * Returns a fixer object that converts a non-string binary expression to a template literal 233 * @param {SourceCodeFixer} fixer The fixer object 234 * @param {ASTNode} node A node that should be converted to a template literal 235 * @returns {Object} A fix for this binary expression 236 */ 237 function fixNonStringBinaryExpression(fixer, node) { 238 const topBinaryExpr = getTopConcatBinaryExpression(node.parent); 239 240 if (hasOctalEscapeSequence(topBinaryExpr)) { 241 return null; 242 } 243 244 return fixer.replaceText(topBinaryExpr, getTemplateLiteral(topBinaryExpr, null, null)); 245 } 246 247 /** 248 * Reports if a given node is string concatenation with non string literals. 249 * @param {ASTNode} node A node to check. 250 * @returns {void} 251 */ 252 function checkForStringConcat(node) { 253 if (!astUtils.isStringLiteral(node) || !isConcatenation(node.parent)) { 254 return; 255 } 256 257 const topBinaryExpr = getTopConcatBinaryExpression(node.parent); 258 259 // Checks whether or not this node had been checked already. 260 if (done[topBinaryExpr.range[0]]) { 261 return; 262 } 263 done[topBinaryExpr.range[0]] = true; 264 265 if (hasNonStringLiteral(topBinaryExpr)) { 266 context.report({ 267 node: topBinaryExpr, 268 messageId: "unexpectedStringConcatenation", 269 fix: fixer => fixNonStringBinaryExpression(fixer, node) 270 }); 271 } 272 } 273 274 return { 275 Program() { 276 done = Object.create(null); 277 }, 278 279 Literal: checkForStringConcat, 280 TemplateLiteral: checkForStringConcat 281 }; 282 } 283}; 284