|
| 1 | +const originalRule = require('eslint/lib/rules/no-param-reassign'); |
| 2 | + |
| 3 | +const {isTypecast} = require('../../ast-utils'); |
| 4 | +const {deepShallowCopy} = require('../../utils'); |
| 5 | + |
| 6 | +module.exports = { |
| 7 | + meta: originalRule.meta, |
| 8 | + create: (context) => { |
| 9 | + const sourceCode = context.getSourceCode(); |
| 10 | + const contextCopy = deepShallowCopy(context); |
| 11 | + |
| 12 | + /** |
| 13 | + * @param {ASTNode} nodeA |
| 14 | + * @param {ASTNode} nodeB |
| 15 | + * @param {string} type |
| 16 | + * @return {boolean} |
| 17 | + */ |
| 18 | + function bothHaveType(nodeA, nodeB, type) { |
| 19 | + return nodeA.type === type && nodeB.type === type; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @param {ASTNode} nodeA |
| 24 | + * @param {ASTNode} nodeB |
| 25 | + * @return {boolean} |
| 26 | + */ |
| 27 | + function bothHaveSameName(nodeA, nodeB) { |
| 28 | + return nodeA.name === nodeB.name; |
| 29 | + } |
| 30 | + |
| 31 | + contextCopy.report = (error) => { |
| 32 | + const {node} = error; |
| 33 | + |
| 34 | + let assignment; |
| 35 | + if (node.parent.type === 'AssignmentExpression') { |
| 36 | + assignment = node.parent; |
| 37 | + } else if (node.parent.type === 'MemberExpression') { |
| 38 | + let ancestor = node.parent; |
| 39 | + while (ancestor.type === 'MemberExpression') { |
| 40 | + ancestor = ancestor.parent; |
| 41 | + } |
| 42 | + |
| 43 | + if (ancestor.type === 'AssignmentExpression') { |
| 44 | + assignment = ancestor; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + if (assignment && assignment.operator === '=') { |
| 49 | + const lhs = assignment.left; |
| 50 | + const rhs = assignment.right; |
| 51 | + |
| 52 | + if (isTypecast(rhs, sourceCode)) { |
| 53 | + if (bothHaveType(lhs, rhs, 'Identifier') && bothHaveSameName(lhs, rhs)) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + if (bothHaveType(lhs, rhs, 'MemberExpression')) { |
| 58 | + let lhsObject = lhs; |
| 59 | + let rhsObject = rhs; |
| 60 | + |
| 61 | + let areIdentical = true; |
| 62 | + while (areIdentical) { |
| 63 | + if (bothHaveType(lhsObject, rhsObject, 'Identifier')) { |
| 64 | + areIdentical = bothHaveSameName(lhsObject, rhsObject); |
| 65 | + } else { |
| 66 | + areIdentical = ( |
| 67 | + bothHaveType(lhsObject.property, rhsObject.property, 'Identifier') && |
| 68 | + bothHaveSameName(lhsObject.property, rhsObject.property) |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + lhsObject = lhsObject.object; |
| 73 | + rhsObject = rhsObject.object; |
| 74 | + |
| 75 | + if (!lhsObject || !rhsObject) { |
| 76 | + break; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + if (areIdentical) { |
| 81 | + return; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + context.report(error); |
| 88 | + }; |
| 89 | + |
| 90 | + return originalRule.create(contextCopy); |
| 91 | + } |
| 92 | +}; |
0 commit comments