Blame view
node_modules/eslint/lib/rules/operator-assignment.js
7.56 KB
f7563de62
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
/** * @fileoverview Rule to replace assignment expressions with operator assignment * @author Brandon Mills */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("../ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Checks whether an operator is commutative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is commutative and has a * shorthand form. */ function isCommutativeOperatorWithShorthand(operator) { return ["*", "&", "^", "|"].indexOf(operator) >= 0; } /** * Checks whether an operator is not commuatative and has an operator assignment * shorthand form. * @param {string} operator Operator to check. * @returns {boolean} True if the operator is not commuatative and has * a shorthand form. */ function isNonCommutativeOperatorWithShorthand(operator) { return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].indexOf(operator) >= 0; } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ /** * Checks whether two expressions reference the same value. For example: * a = a * a.b = a.b * a[0] = a[0] * a['b'] = a['b'] * @param {ASTNode} a Left side of the comparison. * @param {ASTNode} b Right side of the comparison. * @returns {boolean} True if both sides match and reference the same value. */ function same(a, b) { if (a.type !== b.type) { return false; } switch (a.type) { case "Identifier": return a.name === b.name; case "Literal": return a.value === b.value; case "MemberExpression": /* * x[0] = x[0] * x[y] = x[y] * x.y = x.y */ return same(a.object, b.object) && same(a.property, b.property); default: return false; } } /** * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and) * toString calls regardless of whether assignment shorthand is used) * @param {ASTNode} node The node on the left side of the expression * @returns {boolean} `true` if the node can be fixed */ function canBeFixed(node) { return node.type === "Identifier" || node.type === "MemberExpression" && node.object.type === "Identifier" && (!node.computed || node.property.type === "Literal"); } module.exports = { meta: { docs: { description: "require or disallow assignment operator shorthand where possible", category: "Stylistic Issues", recommended: false }, schema: [ { enum: ["always", "never"] } ], fixable: "code" }, create(context) { const sourceCode = context.getSourceCode(); /** * Returns the operator token of an AssignmentExpression or BinaryExpression * @param {ASTNode} node An AssignmentExpression or BinaryExpression node * @returns {Token} The operator token in the node */ function getOperatorToken(node) { return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator); } /** * Ensures that an assignment uses the shorthand form where possible. * @param {ASTNode} node An AssignmentExpression node. * @returns {void} */ function verify(node) { if (node.operator !== "=" || node.right.type !== "BinaryExpression") { return; } const left = node.left; const expr = node.right; const operator = expr.operator; if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) { if (same(left, expr.left)) { context.report({ node, message: "Assignment can be replaced with operator assignment.", fix(fixer) { if (canBeFixed(left)) { const equalsToken = getOperatorToken(node); const operatorToken = getOperatorToken(expr); const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]); const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]); return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`); } return null; } }); } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) { /* * This case can't be fixed safely. * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would * change the execution order of the valueOf() functions. */ context.report({ node, message: "Assignment can be replaced with operator assignment." }); } } } /** * Warns if an assignment expression uses operator assignment shorthand. * @param {ASTNode} node An AssignmentExpression node. * @returns {void} */ function prohibit(node) { if (node.operator !== "=") { context.report({ node, message: "Unexpected operator assignment shorthand.", fix(fixer) { if (canBeFixed(node.left)) { const operatorToken = getOperatorToken(node); const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]); const newOperator = node.operator.slice(0, -1); let rightText; // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side. if ( astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) && !astUtils.isParenthesised(sourceCode, node.right) ) { rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`; } else { rightText = sourceCode.text.slice(operatorToken.range[1], node.range[1]); } return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`); } return null; } }); } } return { AssignmentExpression: context.options[0] !== "never" ? verify : prohibit }; } }; |