-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): [no-unnecessary-parameter-property-assignment] add new rule #8903
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
JoshuaKGoldberg
merged 10 commits into
typescript-eslint:main
from
yeonjuan:new-rule/7045
Jul 6, 2024
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b936c86
feat(eslint-plugin): [no-unnecessary-property-assignment] add new rule
yeonjuan 8ec7665
Merge branch 'main' into new-rule/7045
yeonjuan 06cc50e
apply reviews
yeonjuan d4867cd
remove useless docs
yeonjuan 400cdde
add comment
yeonjuan 68902d8
fix typo
yeonjuan 128e3b5
update snapshots
yeonjuan 49cd5d4
Merge branch 'main' into new-rule/7045
yeonjuan d22cb8b
apply review
yeonjuan b2690e4
trigger action
yeonjuan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
packages/eslint-plugin/docs/rules/no-unnecessary-parameter-property-assignment.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
--- | ||
description: 'Disallow unnecessary assignment of constructor property parameter.' | ||
--- | ||
|
||
import Tabs from '@theme/Tabs'; | ||
import TabItem from '@theme/TabItem'; | ||
|
||
> 🛑 This file is source code, not the primary documentation location! 🛑 | ||
> | ||
> See **https://typescript-eslint.io/rules/no-unnecessary-parameter-property-assignment** for documentation. | ||
|
||
[TypeScript's parameter properties](https://www.typescriptlang.org/docs/handbook/2/classes.html#parameter-properties) allow creating and initializing a member in one place. | ||
Therefore, in most cases, it is not necessary to assign parameter properties of the same name to members within a constructor. | ||
|
||
## Examples | ||
|
||
<Tabs> | ||
<TabItem value="❌ Incorrect"> | ||
|
||
```ts | ||
class Foo { | ||
constructor(public bar: string) { | ||
this.bar = bar; | ||
} | ||
} | ||
``` | ||
|
||
</TabItem> | ||
<TabItem value="✅ Correct"> | ||
|
||
```ts | ||
class Foo { | ||
constructor(public bar: string) {} | ||
} | ||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
## When Not To Use It | ||
|
||
If you don't use parameter properties, you can ignore this rule. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
233 changes: 233 additions & 0 deletions
233
packages/eslint-plugin/src/rules/no-unnecessary-parameter-property-assignment.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,233 @@ | ||
import { DefinitionType } from '@typescript-eslint/scope-manager'; | ||
import type { TSESTree } from '@typescript-eslint/utils'; | ||
import { AST_NODE_TYPES, ASTUtils } from '@typescript-eslint/utils'; | ||
|
||
import { createRule, getStaticStringValue, nullThrows } from '../util'; | ||
|
||
const UNNECESSARY_OPERATORS = new Set(['=', '&&=', '||=', '??=']); | ||
|
||
export default createRule({ | ||
name: 'no-unnecessary-parameter-property-assignment', | ||
meta: { | ||
docs: { | ||
description: | ||
'Disallow unnecessary assignment of constructor property parameter', | ||
}, | ||
fixable: 'code', | ||
messages: { | ||
unnecessaryAssign: | ||
'This assignment is unnecessary since it is already assigned by a parameter property.', | ||
}, | ||
schema: [], | ||
type: 'suggestion', | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
const reportInfoStack: { | ||
assignedBeforeUnnecessary: Set<string>; | ||
assignedBeforeConstructor: Set<string>; | ||
unnecessaryAssignments: { | ||
name: string; | ||
node: TSESTree.AssignmentExpression; | ||
}[]; | ||
}[] = []; | ||
|
||
function isThisMemberExpression( | ||
node: TSESTree.Node, | ||
): node is TSESTree.MemberExpression { | ||
return ( | ||
node.type === AST_NODE_TYPES.MemberExpression && | ||
node.object.type === AST_NODE_TYPES.ThisExpression | ||
); | ||
} | ||
|
||
function getPropertyName(node: TSESTree.Node): string | null { | ||
if (!isThisMemberExpression(node)) { | ||
return null; | ||
} | ||
|
||
if (node.property.type === AST_NODE_TYPES.Identifier) { | ||
return node.property.name; | ||
} | ||
if (node.computed) { | ||
return getStaticStringValue(node.property); | ||
} | ||
return null; | ||
} | ||
|
||
function findParentFunction( | ||
node: TSESTree.Node | undefined, | ||
): | ||
| TSESTree.FunctionExpression | ||
| TSESTree.FunctionDeclaration | ||
| TSESTree.ArrowFunctionExpression | ||
| undefined { | ||
if ( | ||
!node || | ||
node.type === AST_NODE_TYPES.FunctionDeclaration || | ||
node.type === AST_NODE_TYPES.FunctionExpression || | ||
node.type === AST_NODE_TYPES.ArrowFunctionExpression | ||
) { | ||
return node; | ||
} | ||
return findParentFunction(node.parent); | ||
} | ||
|
||
function findParentPropertyDefinition( | ||
node: TSESTree.Node | undefined, | ||
): TSESTree.PropertyDefinition | undefined { | ||
if (!node || node.type === AST_NODE_TYPES.PropertyDefinition) { | ||
return node; | ||
} | ||
return findParentPropertyDefinition(node.parent); | ||
} | ||
|
||
function isConstructorFunctionExpression( | ||
node: TSESTree.Node | undefined, | ||
): node is TSESTree.FunctionExpression { | ||
return ( | ||
node?.type === AST_NODE_TYPES.FunctionExpression && | ||
ASTUtils.isConstructor(node.parent) | ||
); | ||
} | ||
|
||
function isReferenceFromParameter(node: TSESTree.Identifier): boolean { | ||
const scope = context.sourceCode.getScope(node); | ||
|
||
const rightRef = scope.references.find( | ||
ref => ref.identifier.name === node.name, | ||
); | ||
return rightRef?.resolved?.defs.at(0)?.type === DefinitionType.Parameter; | ||
} | ||
|
||
function isParameterPropertyWithName( | ||
node: TSESTree.Parameter, | ||
name: string, | ||
): boolean { | ||
return ( | ||
node.type === AST_NODE_TYPES.TSParameterProperty && | ||
((node.parameter.type === AST_NODE_TYPES.Identifier && // constructor (public foo) {} | ||
node.parameter.name === name) || | ||
(node.parameter.type === AST_NODE_TYPES.AssignmentPattern && // constructor (public foo = 1) {} | ||
node.parameter.left.type === AST_NODE_TYPES.Identifier && | ||
node.parameter.left.name === name)) | ||
); | ||
} | ||
|
||
function getIdentifier(node: TSESTree.Node): TSESTree.Identifier | null { | ||
if (node.type === AST_NODE_TYPES.Identifier) { | ||
return node; | ||
} | ||
if ( | ||
node.type === AST_NODE_TYPES.TSAsExpression || | ||
node.type === AST_NODE_TYPES.TSNonNullExpression | ||
) { | ||
return getIdentifier(node.expression); | ||
} | ||
return null; | ||
} | ||
|
||
function isArrowIIFE(node: TSESTree.Node): boolean { | ||
return ( | ||
node.type === AST_NODE_TYPES.ArrowFunctionExpression && | ||
node.parent.type === AST_NODE_TYPES.CallExpression | ||
); | ||
} | ||
|
||
return { | ||
ClassBody(): void { | ||
reportInfoStack.push({ | ||
unnecessaryAssignments: [], | ||
assignedBeforeUnnecessary: new Set(), | ||
assignedBeforeConstructor: new Set(), | ||
}); | ||
}, | ||
'ClassBody:exit'(): void { | ||
const { unnecessaryAssignments, assignedBeforeConstructor } = | ||
nullThrows(reportInfoStack.pop(), 'The top stack should exist'); | ||
unnecessaryAssignments.forEach(({ name, node }) => { | ||
if (assignedBeforeConstructor.has(name)) { | ||
return; | ||
} | ||
context.report({ | ||
node, | ||
messageId: 'unnecessaryAssign', | ||
}); | ||
}); | ||
}, | ||
'PropertyDefinition AssignmentExpression'( | ||
node: TSESTree.AssignmentExpression, | ||
): void { | ||
const name = getPropertyName(node.left); | ||
|
||
if (!name) { | ||
return; | ||
} | ||
|
||
const functionNode = findParentFunction(node); | ||
if (functionNode) { | ||
if ( | ||
!( | ||
isArrowIIFE(functionNode) && | ||
findParentPropertyDefinition(node)?.value === functionNode.parent | ||
) | ||
) { | ||
return; | ||
} | ||
} | ||
|
||
const { assignedBeforeConstructor } = nullThrows( | ||
reportInfoStack.at(-1), | ||
'The top stack should exist', | ||
); | ||
assignedBeforeConstructor.add(name); | ||
}, | ||
"MethodDefinition[kind='constructor'] > FunctionExpression AssignmentExpression"( | ||
node: TSESTree.AssignmentExpression, | ||
): void { | ||
const leftName = getPropertyName(node.left); | ||
|
||
if (!leftName) { | ||
return; | ||
} | ||
|
||
let functionNode = findParentFunction(node); | ||
if (functionNode && isArrowIIFE(functionNode)) { | ||
functionNode = findParentFunction(functionNode.parent); | ||
} | ||
|
||
if (!isConstructorFunctionExpression(functionNode)) { | ||
return; | ||
} | ||
|
||
const { assignedBeforeUnnecessary, unnecessaryAssignments } = | ||
nullThrows( | ||
reportInfoStack.at(reportInfoStack.length - 1), | ||
'The top of stack should exist', | ||
); | ||
|
||
if (!UNNECESSARY_OPERATORS.has(node.operator)) { | ||
assignedBeforeUnnecessary.add(leftName); | ||
return; | ||
} | ||
|
||
const rightId = getIdentifier(node.right); | ||
|
||
if (leftName !== rightId?.name || !isReferenceFromParameter(rightId)) { | ||
return; | ||
} | ||
|
||
const hasParameterProperty = functionNode.params.some(param => | ||
isParameterPropertyWithName(param, rightId.name), | ||
); | ||
|
||
if (hasParameterProperty && !assignedBeforeUnnecessary.has(leftName)) { | ||
unnecessaryAssignments.push({ | ||
name: leftName, | ||
node, | ||
}); | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
22 changes: 22 additions & 0 deletions
22
...ugin/tests/docs-eslint-output-snapshots/no-unnecessary-parameter-property-assignment.shot
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this true? I'm not able to get it to fix my code, and I don't see where a fixer is passed to
context.report
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Aha! You're right - this was an oversight. eslint/eslint#18008 would have caught it.
Are you up for filing an issue and/or sending a PR @dasa? It'd be a great contribution 😁