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