Skip to content
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

feat(eslint-plugin): [consistent-generic-constructors] add rule #4924

Merged

Conversation

Josh-Cena
Copy link
Contributor

@Josh-Cena Josh-Cena commented May 7, 2022

PR Checklist

Overview

This PR adds a rule consistent-generic-constructors that will report one of:

  • lhs: When a class is new'ed, there's a type parameter on the callee, but no annotation on the variable;
  • rhs: When a class is new'ed, there's an annotation with type parameters on the variable but no type parameters on the callee, and the two names match.

Haven't written much docs, want to get settled on the API design first.

@nx-cloud
Copy link

nx-cloud bot commented May 7, 2022

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 1bdedec. As they complete they will appear below. Click to see the status, the terminal output, and the build insights.

📂 See all runs for this branch


Successfully ran 47 targets

Sent with 💌 from NxCloud.

@typescript-eslint
Copy link
Contributor

typescript-eslint bot commented May 7, 2022

Thanks for the PR, @Josh-Cena!

typescript-eslint is a 100% community driven project, and we are incredibly grateful that you are contributing to that community.

The core maintainers work on this in their personal time, so please understand that it may not be possible for them to review your work immediately.

Thanks again!


🙏 Please, if you or your company is finding typescript-eslint valuable, help us sustain the project by sponsoring it transparently on https://opencollective.com/typescript-eslint. As a thank you, your profile/company logo will be added to our main README which receives thousands of unique visitors per day.

@netlify
Copy link

netlify bot commented May 7, 2022

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit 1bdedec
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/6295fbfe81fd140008cd6dea
😎 Deploy Preview https://deploy-preview-4924--typescript-eslint.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

if (
!rhs ||
rhs.type !== AST_NODE_TYPES.NewExpression ||
rhs.callee.type !== AST_NODE_TYPES.Identifier
) {
return;
}
if (
lhs &&
(lhs.type !== AST_NODE_TYPES.TSTypeReference ||
lhs.typeName.type !== AST_NODE_TYPES.Identifier)
) {
return;
}
Copy link
Contributor Author

@Josh-Cena Josh-Cena May 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally these refinements should be done in the selector, but then I can't get refined types without doing a lot of ugly assertions.

@Josh-Cena Josh-Cena force-pushed the consistent-generic-constructor branch from 03dca0c to 8e5d39f Compare May 7, 2022
@codecov
Copy link

codecov bot commented May 7, 2022

Codecov Report

Merging #4924 (1bdedec) into main (c9c0569) will increase coverage by 2.12%.
The diff coverage is 93.93%.

@@            Coverage Diff             @@
##             main    #4924      +/-   ##
==========================================
+ Coverage   91.70%   93.83%   +2.12%     
==========================================
  Files         362      287      -75     
  Lines       12181     9871    -2310     
  Branches     3530     2950     -580     
==========================================
- Hits        11171     9262    -1909     
+ Misses        661      329     -332     
+ Partials      349      280      -69     
Flag Coverage Δ
unittest 93.83% <93.93%> (+2.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
packages/eslint-plugin/src/configs/all.ts 100.00% <ø> (ø)
packages/eslint-plugin/src/configs/strict.ts 100.00% <ø> (ø)
...lugin/src/rules/consistent-generic-constructors.ts 93.93% <93.93%> (ø)
packages/utils/src/ts-eslint/SourceCode.ts
...plugin-internal/src/rules/prefer-ast-types-enum.ts
packages/utils/src/eslint-utils/RuleTester.ts
...s/utils/src/ast-utils/eslint-utils/astUtilities.ts
packages/utils/src/ts-eslint-scope/Referencer.ts
...-estree/src/create-program/createProjectProgram.ts
packages/type-utils/src/getDeclaration.ts
... and 69 more

@bradzacher bradzacher added the enhancement: new plugin rule label May 10, 2022
Copy link
Contributor

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Great start, thanks for working on this! I recently felt this pain 😄 .

Requesting changes on the terminology, unit tests, and working a bit on simplifying the code with queries & types.

fixable: 'code',
schema: [
{
enum: ['lhs', 'rhs'],
Copy link
Contributor

@JoshuaKGoldberg JoshuaKGoldberg May 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm under the impression we generally try to use objects for the schemas. They're a bit more future-proof and enforce using a property key to explain what the object is for. Only a few rules still have an enum schema.

type: "object" with additionalProperties: false is preferred.

(are there docs on this anywhere in this project or ESLint core? we should write some somewhere if not...)

Copy link
Contributor Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String option is preferred when a rule enforces two kinds of styles, and the rule needs to know which side you are on to be functional at all. Object option is used when you are making refinements to the given style. To give a few examples:

I noticed that we tend to use an object containing a prefer property, but IMO that deviates from ESLint core's API design😅 Sometimes ESLint core would have both string and object, like func-name-matching. When you really look into it, you would understand the differing semantics between string and object.

defaultOptions: ['rhs'],
create(context, [mode]) {
return {
VariableDeclarator(node: TSESTree.VariableDeclarator): void {
Copy link
Contributor

@JoshuaKGoldberg JoshuaKGoldberg May 13, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah the types for these queries can be tricky. More support of us using fancy template literal magicks to parse them (#4065).

Going off the "complex types are from complex code" philosophy: how about splitting this into two queries? VariableDeclarator[init.callee.type='Identifier'][init.type='NewExpression'] could run just the right-hand-side logic.

Search NodeWithModifiers and TypeParameterWithConstraint for examples of places where we've had to manually adjust node types in the past.

Copy link
Contributor Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not particularly good at AST selectors, so I always felt a bit cornered when I have to use them...

Also, we simultaneously need lhs and rhs, and there are a few cases (especially lhs.typeName.name !== rhs.callee.name) where we kind of depend on both for refinement, so I've kept it like this.

Copy link
Contributor Author

@Josh-Cena Josh-Cena May 14, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried, it was ugly refined types like

type TargetVariableDeclarator = TSESTree.VariableDeclarator & {
  init: TSESTree.VariableDeclarator["init"] & {
    type: AST_NODE_TYPES.NewExpression;
    callee: Extract<TSESTree.VariableDeclarator["init"], { callee: unknown }>["callee"] & {
      type: AST_NODE_TYPES.Identifier;
    }
  };
};

Combined with ugly selectors😇 I suggest we don't do it?

@JoshuaKGoldberg JoshuaKGoldberg added the awaiting response label May 13, 2022
@Josh-Cena Josh-Cena force-pushed the consistent-generic-constructor branch from e994a58 to 867152a Compare May 14, 2022
@Josh-Cena Josh-Cena requested a review from JoshuaKGoldberg May 16, 2022
@bradzacher bradzacher removed the awaiting response label May 16, 2022
@Josh-Cena Josh-Cena requested review from armano2 and bradzacher May 30, 2022
@JoshuaKGoldberg
Copy link
Contributor

JoshuaKGoldberg commented May 30, 2022

Ah sorry this fell off my radar! I'd meant to re-review it but got swamped with other things. It might be a day or three before I can give it a deep look again 😞

@Josh-Cena
Copy link
Contributor Author

Josh-Cena commented May 30, 2022

No worries, I almost forgot about it as well...

- If it's set to `constructor` (default), type arguments that **only** appear on the type annotation are disallowed.
- If it's set to `type-annotation`, type arguments that **only** appear on the constructor are disallowed.
Copy link
Member

@bradzacher bradzacher May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a nitpick / personal preference

personally I have found that an object for the options is better than a string.
The issue with starting at a string is that if later you want to add options... well you're stuck and you have to support the string and the object form until you remember to breaking-change remove it (if you remember... which we often don't 😓).

Using an object is also nice as it is self-documenting in a way.

i.e.

['error', 'constructor']
// vs
['error', {prefer: 'constructor'}]

Copy link
Contributor Author

@Josh-Cena Josh-Cena May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, we should have both—i.e., if we have enhancement options in the future, those should be put third. ESLint follows this convention, e.g.

"arrow-body-style": ["error", "as-needed", { "requireReturnForObjectLiteral": true }]

The logic is that the rule needs the primary option (do we use constructor or type-annotation?) to be functional at all, and enhancement options only tweak existing behaviors, instead of totally flipping it.

See #4924 (comment)

lhs.typeName.type !== AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name)
Copy link
Member

@bradzacher bradzacher May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: do we want to handle namespaced names like
const foo: immutable.Set<string> = new immutable.Set();

Copy link
Contributor Author

@Josh-Cena Josh-Cena May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah we should... is there a utility function to match potentially nested qualified names?

Copy link
Member

@bradzacher bradzacher May 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't - I don't think it's something we do all that much!

Copy link
Member

@bradzacher bradzacher Jun 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's leave it off for now - we can add it in later.
It's not super common to be doing this.

Copy link
Member

@bradzacher bradzacher left a comment

this is looking good to me!

lhs.typeName.type !== AST_NODE_TYPES.Identifier ||
lhs.typeName.name !== rhs.callee.name)
Copy link
Member

@bradzacher bradzacher Jun 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's leave it off for now - we can add it in later.
It's not super common to be doing this.

@bradzacher bradzacher changed the title feat(eslint-plugin): new rule consistent-generic-constructors feat(eslint-plugin): [consistent-generic-constructors] add rule Jun 10, 2022
@bradzacher bradzacher merged commit 921cdf1 into typescript-eslint:main Jun 10, 2022
39 checks passed
@Josh-Cena Josh-Cena deleted the consistent-generic-constructor branch Jun 10, 2022
crapStone pushed a commit to Calciumdibromid/CaBr2 that referenced this issue Jun 17, 2022
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.27.1` -> `5.28.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2feslint-plugin/5.27.1/5.28.0) |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint) | devDependencies | minor | [`5.27.1` -> `5.28.0`](https://renovatebot.com/diffs/npm/@typescript-eslint%2fparser/5.27.1/5.28.0) |

---

### Release Notes

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/eslint-plugin)</summary>

### [`v5.28.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#&#8203;5280-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5271v5280-2022-06-13)

[Compare Source](typescript-eslint/typescript-eslint@v5.27.1...v5.28.0)

##### Bug Fixes

-   \[TS4.7] allow visiting of typeParameters in TSTypeQuery ([#&#8203;5166](typescript-eslint/typescript-eslint#5166)) ([dc1f930](typescript-eslint/typescript-eslint@dc1f930))
-   **eslint-plugin:** \[space-infix-ops] support for optional property without type ([#&#8203;5155](typescript-eslint/typescript-eslint#5155)) ([1f25daf](typescript-eslint/typescript-eslint@1f25daf))

##### Features

-   **eslint-plugin:** \[consistent-generic-constructors] add rule ([#&#8203;4924](typescript-eslint/typescript-eslint#4924)) ([921cdf1](typescript-eslint/typescript-eslint@921cdf1))

#### [5.27.1](typescript-eslint/typescript-eslint@v5.27.0...v5.27.1) (2022-06-06)

##### Bug Fixes

-   **eslint-plugin:** \[space-infix-ops] correct PropertyDefinition with typeAnnotation ([#&#8203;5113](typescript-eslint/typescript-eslint#5113)) ([d320174](typescript-eslint/typescript-eslint@d320174))
-   **eslint-plugin:** \[space-infix-ops] regression fix for conditional types ([#&#8203;5135](typescript-eslint/typescript-eslint#5135)) ([e5238c8](typescript-eslint/typescript-eslint@e5238c8))
-   **eslint-plugin:** \[space-infix-ops] regression fix for type aliases ([#&#8203;5138](typescript-eslint/typescript-eslint#5138)) ([4e13deb](typescript-eslint/typescript-eslint@4e13deb))

</details>

<details>
<summary>typescript-eslint/typescript-eslint (@&#8203;typescript-eslint/parser)</summary>

### [`v5.28.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/parser/CHANGELOG.md#&#8203;5280-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5271v5280-2022-06-13)

[Compare Source](typescript-eslint/typescript-eslint@v5.27.1...v5.28.0)

**Note:** Version bump only for package [@&#8203;typescript-eslint/parser](https://github.com/typescript-eslint/parser)

#### [5.27.1](typescript-eslint/typescript-eslint@v5.27.0...v5.27.1) (2022-06-06)

**Note:** Version bump only for package [@&#8203;typescript-eslint/parser](https://github.com/typescript-eslint/parser)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

 **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about these updates again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, click this checkbox.

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).

Co-authored-by: cabr2-bot <cabr2.help@gmail.com>
Reviewed-on: https://codeberg.org/Calciumdibromid/CaBr2/pulls/1409
Reviewed-by: Epsilon_02 <epsilon_02@noreply.codeberg.org>
Co-authored-by: Calciumdibromid Bot <cabr2_bot@noreply.codeberg.org>
Co-committed-by: Calciumdibromid Bot <cabr2_bot@noreply.codeberg.org>
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jul 11, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement: new plugin rule
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants