Skip to content

Commit

Permalink
allow overrides that add annotations (dart-lang#1832)
Browse files Browse the repository at this point in the history
* allow overrides that add annotations

* grammar

* updated doc
  • Loading branch information
pq authored Nov 13, 2019
1 parent 30d0e92 commit fbfb689
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
18 changes: 14 additions & 4 deletions lib/src/rules/unnecessary_overrides.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ class A extends B {
}
```
It's valid to override method for the following cases:
It's valid to override a member in the following cases:
* if a type (return type or a parameter type) is not the exactly the same as the
super method,
* if `covariant` keyword is added to one of the parameter,
* if documentation comments are present on the method.
* if the `covariant` keyword is added to one of the parameters,
* if documentation comments are present on the member,
* if the member has annotations other than `@override`.
`noSuchMethod` is a special method and is not checked by this rule.
Expand Down Expand Up @@ -106,7 +107,7 @@ abstract class _AbstractUnnecessaryOverrideVisitor extends SimpleAstVisitor {

inheritedMethod = getInheritedElement(node);
declaration = node;
if (inheritedMethod != null && _haveSameDeclaration()) {
if (inheritedMethod != null && !_addsMetadata() && _haveSameDeclaration()) {
node.body.accept(this);
}
}
Expand All @@ -126,6 +127,15 @@ abstract class _AbstractUnnecessaryOverrideVisitor extends SimpleAstVisitor {
rule.reportLint(declaration.name);
}

bool _addsMetadata() {
for (var annotation in declaration.declaredElement.metadata) {
if (!annotation.isOverride) {
return true;
}
}
return false;
}

bool _haveSameDeclaration() {
if (declaration.declaredElement.returnType != inheritedMethod.returnType) {
return false;
Expand Down
14 changes: 13 additions & 1 deletion test/rules/unnecessary_overrides.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@

// test w/ `pub run test -N unnecessary_overrides`

class _MyAnnotation {
const _MyAnnotation();
}

const _MyAnnotation myAnnotation = _MyAnnotation();

class Base {
int get x => 0;
set x(other) {}
Expand All @@ -15,6 +21,8 @@ class Base {
int m3({int a, int b}) => 0;
int operator +(other) => 0;
Base operator ~()=> null;
@override
int get hashCode => 13;
}

class Parent extends Base {
Expand Down Expand Up @@ -46,6 +54,10 @@ class Parent extends Base {

@override
Base operator ~()=> ~super; // LINT

@override
@myAnnotation
int get hashCode => super.hashCode; // OK
}

class Okay extends Parent {
Expand Down Expand Up @@ -186,4 +198,4 @@ class E extends C {
/// it's ok to override to provide better documentation
@override
num get g => super.g; // OK
}
}

0 comments on commit fbfb689

Please sign in to comment.