Actualizacion maquina principal
[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 commuatative and has an operator assignment
30  * shorthand form.
31  * @param   {string}  operator Operator to check.
32  * @returns {boolean}          True if the operator is not commuatative 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  * Checks whether two expressions reference the same value. For example:
45  *     a = a
46  *     a.b = a.b
47  *     a[0] = a[0]
48  *     a['b'] = a['b']
49  * @param   {ASTNode} a Left side of the comparison.
50  * @param   {ASTNode} b Right side of the comparison.
51  * @returns {boolean}   True if both sides match and reference the same value.
52  */
53 function same(a, b) {
54     if (a.type !== b.type) {
55         return false;
56     }
57
58     switch (a.type) {
59         case "Identifier":
60             return a.name === b.name;
61
62         case "Literal":
63             return a.value === b.value;
64
65         case "MemberExpression":
66
67             /*
68              * x[0] = x[0]
69              * x[y] = x[y]
70              * x.y = x.y
71              */
72             return same(a.object, b.object) && same(a.property, b.property);
73
74         case "ThisExpression":
75             return true;
76
77         default:
78             return false;
79     }
80 }
81
82 /**
83  * Determines if the left side of a node can be safely fixed (i.e. if it activates the same getters/setters and)
84  * toString calls regardless of whether assignment shorthand is used)
85  * @param {ASTNode} node The node on the left side of the expression
86  * @returns {boolean} `true` if the node can be fixed
87  */
88 function canBeFixed(node) {
89     return (
90         node.type === "Identifier" ||
91         (
92             node.type === "MemberExpression" &&
93             (node.object.type === "Identifier" || node.object.type === "ThisExpression") &&
94             (!node.computed || node.property.type === "Literal")
95         )
96     );
97 }
98
99 module.exports = {
100     meta: {
101         type: "suggestion",
102
103         docs: {
104             description: "require or disallow assignment operator shorthand where possible",
105             category: "Stylistic Issues",
106             recommended: false,
107             url: "https://eslint.org/docs/rules/operator-assignment"
108         },
109
110         schema: [
111             {
112                 enum: ["always", "never"]
113             }
114         ],
115
116         fixable: "code",
117         messages: {
118             replaced: "Assignment can be replaced with operator assignment.",
119             unexpected: "Unexpected operator assignment shorthand."
120         }
121     },
122
123     create(context) {
124
125         const sourceCode = context.getSourceCode();
126
127         /**
128          * Returns the operator token of an AssignmentExpression or BinaryExpression
129          * @param {ASTNode} node An AssignmentExpression or BinaryExpression node
130          * @returns {Token} The operator token in the node
131          */
132         function getOperatorToken(node) {
133             return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
134         }
135
136         /**
137          * Ensures that an assignment uses the shorthand form where possible.
138          * @param   {ASTNode} node An AssignmentExpression node.
139          * @returns {void}
140          */
141         function verify(node) {
142             if (node.operator !== "=" || node.right.type !== "BinaryExpression") {
143                 return;
144             }
145
146             const left = node.left;
147             const expr = node.right;
148             const operator = expr.operator;
149
150             if (isCommutativeOperatorWithShorthand(operator) || isNonCommutativeOperatorWithShorthand(operator)) {
151                 if (same(left, expr.left)) {
152                     context.report({
153                         node,
154                         messageId: "replaced",
155                         fix(fixer) {
156                             if (canBeFixed(left)) {
157                                 const equalsToken = getOperatorToken(node);
158                                 const operatorToken = getOperatorToken(expr);
159                                 const leftText = sourceCode.getText().slice(node.range[0], equalsToken.range[0]);
160                                 const rightText = sourceCode.getText().slice(operatorToken.range[1], node.right.range[1]);
161
162                                 // Check for comments that would be removed.
163                                 if (sourceCode.commentsExistBetween(equalsToken, operatorToken)) {
164                                     return null;
165                                 }
166
167                                 return fixer.replaceText(node, `${leftText}${expr.operator}=${rightText}`);
168                             }
169                             return null;
170                         }
171                     });
172                 } else if (same(left, expr.right) && isCommutativeOperatorWithShorthand(operator)) {
173
174                     /*
175                      * This case can't be fixed safely.
176                      * If `a` and `b` both have custom valueOf() behavior, then fixing `a = b * a` to `a *= b` would
177                      * change the execution order of the valueOf() functions.
178                      */
179                     context.report({
180                         node,
181                         messageId: "replaced"
182                     });
183                 }
184             }
185         }
186
187         /**
188          * Warns if an assignment expression uses operator assignment shorthand.
189          * @param   {ASTNode} node An AssignmentExpression node.
190          * @returns {void}
191          */
192         function prohibit(node) {
193             if (node.operator !== "=") {
194                 context.report({
195                     node,
196                     messageId: "unexpected",
197                     fix(fixer) {
198                         if (canBeFixed(node.left)) {
199                             const firstToken = sourceCode.getFirstToken(node);
200                             const operatorToken = getOperatorToken(node);
201                             const leftText = sourceCode.getText().slice(node.range[0], operatorToken.range[0]);
202                             const newOperator = node.operator.slice(0, -1);
203                             let rightText;
204
205                             // Check for comments that would be duplicated.
206                             if (sourceCode.commentsExistBetween(firstToken, operatorToken)) {
207                                 return null;
208                             }
209
210                             // If this change would modify precedence (e.g. `foo *= bar + 1` => `foo = foo * (bar + 1)`), parenthesize the right side.
211                             if (
212                                 astUtils.getPrecedence(node.right) <= astUtils.getPrecedence({ type: "BinaryExpression", operator: newOperator }) &&
213                                 !astUtils.isParenthesised(sourceCode, node.right)
214                             ) {
215                                 rightText = `${sourceCode.text.slice(operatorToken.range[1], node.right.range[0])}(${sourceCode.getText(node.right)})`;
216                             } else {
217                                 const firstRightToken = sourceCode.getFirstToken(node.right);
218                                 let rightTextPrefix = "";
219
220                                 if (
221                                     operatorToken.range[1] === firstRightToken.range[0] &&
222                                     !astUtils.canTokensBeAdjacent(newOperator, firstRightToken)
223                                 ) {
224                                     rightTextPrefix = " "; // foo+=+bar -> foo= foo+ +bar
225                                 }
226
227                                 rightText = `${rightTextPrefix}${sourceCode.text.slice(operatorToken.range[1], node.range[1])}`;
228                             }
229
230                             return fixer.replaceText(node, `${leftText}= ${leftText}${newOperator}${rightText}`);
231                         }
232                         return null;
233                     }
234                 });
235             }
236         }
237
238         return {
239             AssignmentExpression: context.options[0] !== "never" ? verify : prohibit
240         };
241
242     }
243 };