1 | /**
|
2 | * @fileoverview disallow unncessary concatenation of template strings
|
3 | * @author Henry Zhu
|
4 | * @copyright 2015 Henry Zhu. All rights reserved.
|
5 | * See LICENSE file in root directory for full license.
|
6 | */
|
7 | ;
|
8 |
|
9 | //------------------------------------------------------------------------------
|
10 | // Requirements
|
11 | //------------------------------------------------------------------------------
|
12 |
|
13 | var astUtils = require("../ast-utils");
|
14 |
|
15 | //------------------------------------------------------------------------------
|
16 | // Helpers
|
17 | //------------------------------------------------------------------------------
|
18 |
|
19 | /**
|
20 | * Checks whether or not a given node is a concatenation.
|
21 | * @param {ASTNode} node - A node to check.
|
22 | * @returns {boolean} `true` if the node is a concatenation.
|
23 | */
|
24 | function isConcatenation(node) {
|
25 | return node.type === "BinaryExpression" && node.operator === "+";
|
26 | }
|
27 |
|
28 | /**
|
29 | * Get's the right most node on the left side of a BinaryExpression with + operator.
|
30 | * @param {ASTNode} node - A BinaryExpression node to check.
|
31 | * @returns {ASTNode} node
|
32 | */
|
33 | function getLeft(node) {
|
34 | var left = node.left;
|
35 | while (isConcatenation(left)) {
|
36 | left = left.right;
|
37 | }
|
38 | return left;
|
39 | }
|
40 |
|
41 | /**
|
42 | * Get's the left most node on the right side of a BinaryExpression with + operator.
|
43 | * @param {ASTNode} node - A BinaryExpression node to check.
|
44 | * @returns {ASTNode} node
|
45 | */
|
46 | function getRight(node) {
|
47 | var right = node.right;
|
48 | while (isConcatenation(right)) {
|
49 | right = right.left;
|
50 | }
|
51 | return right;
|
52 | }
|
53 |
|
54 | //------------------------------------------------------------------------------
|
55 | // Rule Definition
|
56 | //------------------------------------------------------------------------------
|
57 |
|
58 | module.exports = function(context) {
|
59 | return {
|
60 | BinaryExpression: function(node) {
|
61 | // check if not concatenation
|
62 | if (node.operator !== "+") {
|
63 | return;
|
64 | }
|
65 |
|
66 | // account for the `foo + "a" + "b"` case
|
67 | var left = getLeft(node);
|
68 | var right = getRight(node);
|
69 |
|
70 | if (astUtils.isStringLiteral(left) &&
|
71 | astUtils.isStringLiteral(right) &&
|
72 | astUtils.isTokenOnSameLine(left, right)
|
73 | ) {
|
74 | // move warning location to operator
|
75 | var operatorToken = context.getTokenAfter(left);
|
76 | while (operatorToken.value !== "+") {
|
77 | operatorToken = context.getTokenAfter(operatorToken);
|
78 | }
|
79 |
|
80 | context.report(
|
81 | node,
|
82 | operatorToken.loc.start,
|
83 | "Unexpected string concatenation of literals.");
|
84 | }
|
85 | }
|
86 | };
|
87 | };
|
88 |
|
89 | module.exports.schema = [];
|