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): add rule call-super-on-override #5848

Closed
wants to merge 18 commits into from

Conversation

mahdi-farnia
Copy link

PR Checklist

Overview

Before:

  1. Warning expected to note that overridden method should call it's super method to prevent missing something!
// Trivia example
class Foo {
  dealloc(): void {
    memory.dealloc();
  }
}

class Bar extends Foo {
  override dealloc(): void {
    console.log("Deallocated"); // note that memory.dealloc() didn't call
  }
}

After:

// Trivia example
class Foo {
  dealloc(): void {
    memory.dealloc();
  }
}

class Bar extends Foo {
  override dealloc(): void {
    console.log("Deallocated"); // note that memory.dealloc() didn't call
    // ^^^ missingSuperMethodCall warning
  }
}

This checking can be disabled via option ignoreMethods: true

  1. Also ordering may be important:

Before:

// Trivia example on drawing a circle with Canvas API
class MyCircle extends Circle {
  override draw(): void {
    this.changeColor("blue");
    super.draw(); // <-- ordering matters here
  }
}

After:

// Trivia example on drawing a circle with Canvas API
class MyCircle extends Circle {
  override draw(): void {
    this.changeColor("blue");
    super.draw();
    // ^^^ topLevel warning
  }
}

This options is disabled by default and can be enabled by topLevel: true

Closes #684

Note about local git history by me: I rewrite it again after one month, and i figured out that the last clone is outdated and i cloned the latest repo and just copied & pasted the file.
Because of that there is no history available for this project.

I rewrite it again after one month, and i figured out that the last
clone is outdated and i cloned the latest repo and just copied & pasted
the file.
Because of that there is no history available for this project.
@nx-cloud
Copy link

nx-cloud bot commented Oct 18, 2022

☁️ Nx Cloud Report

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


🟥 Failed Commands
nx run-many --target=lint --parallel
✅ Successfully ran 45 targets

Sent with 💌 from NxCloud.

@typescript-eslint
Copy link
Contributor

Thanks for the PR, @mahdi-farnia!

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 Oct 18, 2022

Deploy Preview for typescript-eslint ready!

Name Link
🔨 Latest commit 2b97414
🔍 Latest deploy log https://app.netlify.com/sites/typescript-eslint/deploys/6410b7554847d10008e3467f
😎 Deploy Preview https://deploy-preview-5848--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.

@codecov
Copy link

codecov bot commented Oct 18, 2022

Codecov Report

Merging #5848 (93e9c16) into main (9eafd87) will increase coverage by 0.01%.
The diff coverage is 90.32%.

❗ Current head 93e9c16 differs from pull request most recent head 2b97414. Consider uploading reports for the commit 2b97414 to get more accurate results

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5848      +/-   ##
==========================================
+ Coverage   85.15%   85.16%   +0.01%     
==========================================
  Files         383      384       +1     
  Lines       13026    13057      +31     
  Branches     3839     3851      +12     
==========================================
+ Hits        11092    11120      +28     
  Misses       1572     1572              
- Partials      362      365       +3     
Flag Coverage Δ
unittest 85.16% <90.32%> (+0.01%) ⬆️

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

Impacted Files Coverage Δ
.../eslint-plugin/src/rules/call-super-on-override.ts 90.32% <90.32%> (ø)

Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Great start! I don't have time to work on this now, so leaving a review for now as usual. As discussed in #684 (comment), anybody can feel free to send a new PR addressing the review. ❤️

@JoshuaKGoldberg JoshuaKGoldberg added the awaiting response Issues waiting for a reply from the OP or another party label Oct 19, 2022
mahdi-farnia and others added 8 commits October 19, 2022 09:57
Unnecessary Information Removed

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
Rule Is Now Off By Default

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
My bad!😱

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
This option is unneeded because users can simply turn off the rule
Support for literal method names & better error message for computed and
non-computed method names.
@bradzacher bradzacher marked this pull request as draft October 19, 2022 11:53
@mahdi-farnia mahdi-farnia marked this pull request as ready for review October 19, 2022 15:58
@bradzacher bradzacher added enhancement: new plugin rule New rule request for eslint-plugin and removed awaiting response Issues waiting for a reply from the OP or another party labels Oct 24, 2022
@JoshuaKGoldberg JoshuaKGoldberg changed the title feat(eslint-plugin): super's overidden method should be called feat(eslint-plugin): super's overridden method should be called Nov 18, 2022
@bradzacher bradzacher changed the title feat(eslint-plugin): super's overridden method should be called feat(eslint-plugin): add rule call-super-on-override Nov 23, 2022
Copy link
Member

@JoshuaKGoldberg JoshuaKGoldberg left a comment

Choose a reason for hiding this comment

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

Getting closer, thanks for continuing to work on this! Unless someone in @typescript-eslint/triage-team disagrees with me, I think we'll want type checking in the rule?

packages/eslint-plugin/src/rules/call-super-on-override.ts Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/call-super-on-override.ts Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/call-super-on-override.ts Outdated Show resolved Hide resolved
if (node.key.type === AST_NODE_TYPES.Identifier) {
methodName = node.key.name;
} else {
methodNameIsLiteral = true;
Copy link
Member

Choose a reason for hiding this comment

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

[Refactor] Aha, a duplication of information! methodNameIsLiteral will always be true if methodNameIsNull is true. So this is using two variables to store a single piece of info. I'd suggest using either a union type or enum to consolidate down to one variable.

For example, the enum form might look something like this (but maybe with different names, I haven't thought too hard about these):

type MethodNameVariant = 'identifier' | 'non-null-literal' | 'null-literal';

packages/eslint-plugin/src/rules/call-super-on-override.ts Outdated Show resolved Hide resolved
packages/eslint-plugin/src/rules/call-super-on-override.ts Outdated Show resolved Hide resolved
// null & undefined can be used as property names, undefined counted as Identifier & null as Literal
methodName =
(node.key as TSESTree.Literal).value?.toString() ?? 'null';
methodNameIsNull = (node.key as TSESTree.Literal).value == null;
Copy link
Member

Choose a reason for hiding this comment

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

node.key as TSESTree.Literal

[Refactor] This as assertion isn't always going to be correct. The TSESTree types are set up to represent all the possible values of properties. The fact that an as was needed to get this code to type check means that the code isn't handling some case that it needs to handle.

Removing the as gives:

Property 'value' does not exist on type 'FunctionExpression | ArrayExpression | ArrayPattern | ArrowFunctionExpression | AssignmentExpression | ... 35 more ... | YieldExpression'.
  Property 'value' does not exist on type 'FunctionExpression'.

...which is true. What if the node's key is a function expression?

class InvalidSample {
  [function () { }]() {
    console.log("Yippee!")
  }
}

This code is wacky (and causes a TypeScript complaint) but someone in the wild might try to run this rule on that code.

Change request: remove all the as assertions from this file, and explicitly handle those odd node edge cases.

Note too that we require high unit test coverage (generally, ~100% if possible) for new rule tests. So this'll need unit tests added for any new logic. You can always run yarn test from packages/eslint-plugin to generate a testing coverage report at packages/eslint-plugin/coverage/lcov-report/index.html (or see the Codecov PR comment for an online viewer).


## When Not To Use It

When you are using TypeScript < 4.3 or you did not set `noImplicitOverride: true` in `CompilerOptions`
Copy link
Member

Choose a reason for hiding this comment

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

A lot of consumers don't use noImplicitOverride. I think we'll still want the rule to be able to work for them... which means it'll have to use rule type checking when there isn't an override operator on a method.

Roughly, that means:

  1. Grabbing the type of the extended class
  2. Checking whether it has a method / function property under the same name

Copy link
Member

Choose a reason for hiding this comment

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

Let's keep conversations threaded, please, so it's easier to have multiple at a time & mark them as open or resolved.

As to how to grab the type of the extended class: you'll need to use the type checker. Have you read our resources on doing that?

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

👋 @mahdi-farnia! Just checking in, is this still something you have time for? No worries if not - I just don't want to leave it hanging.

@mahdi-farnia
Copy link
Author

I'll name this laziness of myself

Sorry about that
I am going to check it tonight ( My country has 12:30 hours difference from US )

I forgot resolving issues after my college exams...🤦‍♂️

Co-authored-by: Josh Goldberg <git@joshuakgoldberg.com>
@mahdi-farnia
Copy link
Author

I need help!
How can grabbing the type of the extended class(es)?
Any article or guid?
@JoshuaKGoldberg

Commit current progress (for now)
@mahdi-farnia
Copy link
Author

Just note that i did not make any progress (for now).
I just applied some suggested changes

I already using astexplorer and ts-ast-viewer

Is there any other tool?

@JoshuaKGoldberg
Copy link
Member

I responded in this thread: #5848 (comment)

@bradzacher bradzacher closed this Mar 19, 2023
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 27, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
awaiting response Issues waiting for a reply from the OP or another party 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: checks if you remembered to call super.method()
3 participants