]>
git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/operator-assignment.js
2 * @fileoverview Rule to replace assignment expressions with operator assignment
3 * @author Brandon Mills
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils
= require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
18 * Checks whether an operator is commutative and has an operator assignment
20 * @param {string} operator Operator to check.
21 * @returns {boolean} True if the operator is commutative and has a
24 function isCommutativeOperatorWithShorthand(operator
) {
25 return ["*", "&", "^", "|"].includes(operator
);
29 * Checks whether an operator is not commutative and has an operator assignment
31 * @param {string} operator Operator to check.
32 * @returns {boolean} True if the operator is not commutative and has
35 function isNonCommutativeOperatorWithShorthand(operator
) {
36 return ["+", "-", "/", "%", "<<", ">>", ">>>", "**"].includes(operator
);
39 //------------------------------------------------------------------------------
41 //------------------------------------------------------------------------------
44 * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
45 * toString calls regardless of whether assignment shorthand is used)
46 * @param {ASTNode} node The node on the left side of the expression
47 * @returns {boolean} `true` if the node can be fixed
49 function canBeFixed(node
) {
51 node
.type
=== "Identifier" ||
53 node
.type
=== "MemberExpression" &&
54 (node
.object
.type
=== "Identifier" || node
.object
.type
=== "ThisExpression") &&
55 (!node
.computed
|| node
.property
.type
=== "Literal")
60 /** @type {import('../shared/types').Rule} */
66 description
: "Require or disallow assignment operator shorthand where possible",
68 url
: "https://eslint.org/docs/rules/operator-assignment"
73 enum: ["always", "never"]
79 replaced
: "Assignment (=) can be replaced with operator assignment ({{operator}}).",
80 unexpected
: "Unexpected operator assignment ({{operator}}) shorthand."
86 const sourceCode
= context
.getSourceCode();
89 * Returns the operator token of an AssignmentExpression or BinaryExpression
90 * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
91 * @returns {Token} The operator token in the node
93 function getOperatorToken(node
) {
94 return sourceCode
.getFirstTokenBetween(node
.left
, node
.right
, token
=> token
.value
=== node
.operator
);
98 * Ensures that an assignment uses the shorthand form where possible.
99 * @param {ASTNode} node An AssignmentExpression node.
102 function verify(node
) {
103 if (node
.operator
!== "=" || node
.right
.type
!== "BinaryExpression") {
107 const left
= node
.left
;
108 const expr
= node
.right
;
109 const operator
= expr
.operator
;
111 if (isCommutativeOperatorWithShorthand(operator
) || isNonCommutativeOperatorWithShorthand(operator
)) {
112 const replacementOperator
= `${operator}=`;
114 if (astUtils
.isSameReference(left
, expr
.left
, true)) {
117 messageId
: "replaced",
118 data
: { operator
: replacementOperator
},
120 if (canBeFixed(left
) && canBeFixed(expr
.left
)) {
121 const equalsToken
= getOperatorToken(node
);
122 const operatorToken
= getOperatorToken(expr
);
123 const leftText
= sourceCode
.getText().slice(node
.range
[0], equalsToken
.range
[0]);
124 const rightText
= sourceCode
.getText().slice(operatorToken
.range
[1], node
.right
.range
[1]);
126 // Check for comments that would be removed.
127 if (sourceCode
.commentsExistBetween(equalsToken
, operatorToken
)) {
131 return fixer
.replaceText(node
, `${leftText}${replacementOperator}${rightText}`);
136 } else if (astUtils
.isSameReference(left
, expr
.right
, true) && isCommutativeOperatorWithShorthand(operator
)) {
139 * This case can't be fixed safely.
140 * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
141 * change the execution order of the valueOf() functions.
145 messageId
: "replaced",
146 data
: { operator
: replacementOperator
}
153 * Warns if an assignment expression uses operator assignment shorthand.
154 * @param {ASTNode} node An AssignmentExpression node.
157 function prohibit(node
) {
158 if (node
.operator
!== "=" && !astUtils
.isLogicalAssignmentOperator(node
.operator
)) {
161 messageId
: "unexpected",
162 data
: { operator
: node
.operator
},
164 if (canBeFixed(node
.left
)) {
165 const firstToken
= sourceCode
.getFirstToken(node
);
166 const operatorToken
= getOperatorToken(node
);
167 const leftText
= sourceCode
.getText().slice(node
.range
[0], operatorToken
.range
[0]);
168 const newOperator
= node
.operator
.slice(0, -1);
171 // Check for comments that would be duplicated.
172 if (sourceCode
.commentsExistBetween(firstToken
, operatorToken
)) {
176 // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
178 astUtils
.getPrecedence(node
.right
) <= astUtils
.getPrecedence({ type
: "BinaryExpression", operator
: newOperator
}) &&
179 !astUtils
.isParenthesised(sourceCode
, node
.right
)
181 rightText
= `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
183 const tokenAfterOperator
= sourceCode
.getTokenAfter(operatorToken
, { includeComments
: true });
184 let rightTextPrefix
= "";
187 operatorToken
.range
[1] === tokenAfterOperator
.range
[0] &&
188 !astUtils
.canTokensBeAdjacent({ type
: "Punctuator", value
: newOperator
}, tokenAfterOperator
)
190 rightTextPrefix
= " "; // foo+=+bar -> foo= foo+ +bar
193 rightText
= `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
196 return fixer
.replaceText(node
, `${leftText}= ${leftText}${newOperator}${rightText}`);
205 AssignmentExpression
: context
.options
[0] !== "never" ? verify
: prohibit