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): [no-mixed-enums] add rule #6102

Merged
merged 13 commits into from Feb 16, 2023

Conversation

JoshuaKGoldberg
Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg commented Nov 27, 2022

PR Checklist

Overview

Adds a no-mixed-enums rule that flags the first member of an enum that mismatches its type compared to previous members. Uses the type checker for this because enum members can sometimes have dynamically computed values:

enum Annoying {
  Gotcha = Math.random()
}

Doesn't ban specifically numeric and/or string member values. Both are extremely common patterns and I don't think there's enough user demand to justify that.

Borrows some documentation from #3891. Thanks 😄

Co-authored-by: @brianconnoly

@nx-cloud
Copy link

nx-cloud bot commented Nov 27, 2022

☁️ Nx Cloud Report

CI is running/has finished running commands for commit 1de4847. 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

Thanks for the PR, @JoshuaKGoldberg!

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.

@netlify
Copy link

netlify bot commented Nov 27, 2022

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit 1de4847
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/63ee7f8c2cb5c300080afa22
😎 Deploy Preview https://deploy-preview-6102--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.

@JoshuaKGoldberg JoshuaKGoldberg marked this pull request as ready for review November 27, 2022 02:41
@codecov
Copy link

codecov bot commented Nov 27, 2022

Codecov Report

Merging #6102 (1de4847) into main (f330e06) will decrease coverage by 0.87%.
The diff coverage is 94.44%.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6102      +/-   ##
==========================================
- Coverage   91.52%   90.66%   -0.87%     
==========================================
  Files         371      374       +3     
  Lines       12651    12823     +172     
  Branches     3717     3777      +60     
==========================================
+ Hits        11579    11626      +47     
- Misses        754      853      +99     
- Partials      318      344      +26     
Flag Coverage Δ
unittest 90.66% <94.44%> (-0.87%) ⬇️

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

Impacted Files Coverage Δ
packages/eslint-plugin/src/rules/no-mixed-enums.ts 94.44% <94.44%> (ø)
packages/typescript-estree/src/convert-comments.ts 57.14% <0.00%> (-42.86%) ⬇️
packages/typescript-estree/src/convert.ts 84.89% <0.00%> (-12.25%) ⬇️
packages/typescript-estree/src/node-utils.ts 83.51% <0.00%> (-7.45%) ⬇️
...escript-estree/src/semantic-or-syntactic-errors.ts 80.00% <0.00%> (-6.67%) ⬇️
...pt-estree/src/parseSettings/createParseSettings.ts 91.30% <0.00%> (-6.20%) ⬇️
...ipt-estree/src/parseSettings/resolveProjectList.ts 91.11% <0.00%> (-4.45%) ⬇️
...ckages/eslint-plugin/src/util/getESLintCoreRule.ts 75.00% <0.00%> (ø)
...nt-plugin/src/rules/no-import-type-side-effects.ts 100.00% <0.00%> (ø)
...-estree/src/parseSettings/getProjectConfigFiles.ts 100.00% <0.00%> (ø)
... and 6 more

@bradzacher bradzacher added enhancement: plugin rule option New rule option for an existing eslint-plugin rule enhancement: new plugin rule New rule request for eslint-plugin and removed enhancement: plugin rule option New rule option for an existing eslint-plugin rule labels Jan 30, 2023
Copy link
Member

@bradzacher bradzacher left a comment

Choose a reason for hiding this comment

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

because enum members can sometimes have dynamically computed values

Note that number enum members are the only ones that are allow to have "complex" computed values:

declare function str(): string;
declare function num(): number;

declare const StRiNgCoNsTrUcToR: { new(): string };
declare const NuMbErCoNsTrUcToR: { new(): number };

enum Foo {
    A = str(),          // invalid
    B = `${'a'}`,       // invalid
    C = str.name,       // invalid
    D = 'a' + 'b',      // valid
    E = new String(''), // invalid
    F = new StRiNgCoNsTrUcToR(), // invalid

    M = num(),          // valid
    N = Number.EPSILON, // valid
    O = 1 + 1,          // valid
    P = new Number(1),  // invalid
    Q = new NuMbErCoNsTrUcToR(), // valid because it's dumb
}

play

This means we don't actually need the typechecker here.
We can simply follow the following logic:

  1. if no initialiser, number
  2. if initialiser
    1. if string literal or template literal, string
    2. if number literal, number
    3. if binary expression,
      1. if all operands are string literals or template literals, string
      2. else number
    4. if member expression, use type information to get the type
    5. else number

There is just one single caveat to this that I can see - enums built from enums:

enum Foo {
    A = 1,
    B = 'a',
}

enum Bar {
    A = Foo.A,
    B = Foo.B,
}

This is valid TS and creates a mixed enum. But IDK if we really care for this case? Could be a documented edge case that we wait for people to comment on? IDK.

TS even optimises `Bar` at transpile time so that it directly uses the literal values...!
var Foo;
(function (Foo) {
    Foo[Foo["A"] = 1] = "A";
    Foo["B"] = "a";
})(Foo || (Foo = {}));
var Bar;
(function (Bar) {
    Bar[Bar["A"] = 1] = "A";
    Bar["B"] = "a";
})(Bar || (Bar = {}));

@bradzacher
Copy link
Member

Looking more, here is another case of valid TS that is dumb, declaration merging:

enum Foo {
    A = 1,
    B = 1,
}
enum Foo {
    C = 'c',
    D = 'd',
}

playground

This will also create a mixed enum. This is much more difficult to handle without types though. I doubt your current code even handles it!

Again, I'd be happy to just document and ignore this case cos this is so so so rare and is really dumb code.

@bradzacher bradzacher added the awaiting response Issues waiting for a reply from the OP or another party label Jan 30, 2023
@JoshuaKGoldberg
Copy link
Member Author

enums built from enums

Oh, I've definitely seen this before. 😬 Thinking I'll try to handle it...

@JoshuaKGoldberg JoshuaKGoldberg removed the awaiting response Issues waiting for a reply from the OP or another party label Feb 5, 2023
Copy link
Member

@bradzacher bradzacher left a comment

Choose a reason for hiding this comment

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

okay - doing some research on the declaration merging case - I think you can only merge enums in the following cases:

  1. if both declarations are in the same file:
    enum Foo { A = 1 }
    enum Foo { B = 2 }
    Foo.A;
    Foo.B;
  2. ambiently via module augmentation
    import {AST_NODE_TYPES} from '@typescript-eslint/types';
    
    declare module '@typescript-eslint/types' {
      enum AST_NODE_TYPES {
        WUT = 'WUT',
      }
    }
  3. via namespace declaration merging
    namespace Test {
      export enum Bar { A = 1 }
    }
    namespace Test {
      export enum Bar { B = 2 }
    }
    Test.Bar.A;
    Test.Bar.B;

playground

With that in mind - we can probably rework this rule to be faster.

WDYT of the following logic:

TSEnumDeclaration(node) {
  let members = node.members;
  if (
    isWithinTSModuleDecl(node) ||
    enumNameHasTwoDeclarationsInScope(node)
  ) {
    members = members.concat(getMergedMembers(node));
  }
  
  let desiredType: 'string' | 'number';
  for (const member of members) {
    const currentType: 'string' | 'number' = 
      getTypeFromAST(member) ?? getTypeFromTypeInfo(member);

    desiredType ??= currentType;
    if (desiredType !== currentType) {
      report(member);
    }
  }
}

This way we stay fast for cases that we know should be fast (which should be the vast, vast majority of code and cases), and we only dip into the slow type info for the weird edge-cases.

WDYT?

@bradzacher bradzacher added the awaiting response Issues waiting for a reply from the OP or another party label Feb 10, 2023
@JoshuaKGoldberg
Copy link
Member Author

Aha you're totally right - thanks for pressing on this! +1. Will do.

It's a pity we can't quite make it to untyped - but yes I do like that this is non-type-checked mostly.

@JoshuaKGoldberg JoshuaKGoldberg marked this pull request as draft February 11, 2023 13:28
@JoshuaKGoldberg JoshuaKGoldberg marked this pull request as ready for review February 15, 2023 00:53
bradzacher
bradzacher previously approved these changes Feb 16, 2023
Copy link
Member

@bradzacher bradzacher left a comment

Choose a reason for hiding this comment

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

overall LGTM!

packages/eslint-plugin/docs/rules/no-mixed-enums.md Outdated Show resolved Hide resolved
packages/eslint-plugin/docs/rules/no-mixed-enums.md Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/no-mixed-enums.ts Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/no-mixed-enums.ts Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/no-mixed-enums.ts Outdated Show resolved Hide resolved
@bradzacher bradzacher removed the awaiting response Issues waiting for a reply from the OP or another party label Feb 16, 2023
Co-authored-by: Brad Zacher <brad.zacher@gmail.com>
@JoshuaKGoldberg JoshuaKGoldberg merged commit 16144d1 into typescript-eslint:main Feb 16, 2023
crapStone pushed a commit to Calciumdibromid/CaBr2 that referenced this pull request Feb 22, 2023
This PR contains the following updates:

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

---

### Release Notes

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

### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/eslint-plugin/CHANGELOG.md#&#8203;5530-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5520v5530-2023-02-20)

[Compare Source](typescript-eslint/typescript-eslint@v5.52.0...v5.53.0)

##### Features

-   **eslint-plugin:** \[consistent-generic-constructors] handle default parameters ([#&#8203;6484](typescript-eslint/typescript-eslint#6484)) ([e8cebce](typescript-eslint/typescript-eslint@e8cebce))
-   **eslint-plugin:** \[no-mixed-enums] add rule ([#&#8203;6102](typescript-eslint/typescript-eslint#6102)) ([16144d1](typescript-eslint/typescript-eslint@16144d1))

</details>

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

### [`v5.53.0`](https://github.com/typescript-eslint/typescript-eslint/blob/HEAD/packages/parser/CHANGELOG.md#&#8203;5530-httpsgithubcomtypescript-eslinttypescript-eslintcomparev5520v5530-2023-02-20)

[Compare Source](typescript-eslint/typescript-eslint@v5.52.0...v5.53.0)

**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, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNC4xNDYuMSIsInVwZGF0ZWRJblZlciI6IjM0LjE0OS4wIn0=-->

Co-authored-by: cabr2-bot <cabr2.help@gmail.com>
Reviewed-on: https://codeberg.org/Calciumdibromid/CaBr2/pulls/1791
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 Feb 24, 2023
@JoshuaKGoldberg JoshuaKGoldberg deleted the no-mixed-enums branch February 3, 2024 16:51
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement: new plugin rule New rule request for eslint-plugin
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Rule proposal: disallow mixed string/numeric enums
2 participants