Skip to content

Commit

Permalink
Report avoid_returning_this on the return statement (#3724)
Browse files Browse the repository at this point in the history
  • Loading branch information
srawlins committed Sep 26, 2022
1 parent a91fbd6 commit 91d8ae3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
9 changes: 3 additions & 6 deletions lib/src/rules/avoid_returning_this.dart
Expand Up @@ -45,10 +45,7 @@ var buffer = StringBuffer()

bool _isFunctionExpression(AstNode node) => node is FunctionExpression;

bool _isReturnStatement(AstNode node) => node is ReturnStatement;

bool _returnsThis(AstNode node) =>
(node as ReturnStatement).expression is ThisExpression;
bool _returnsThis(ReturnStatement node) => node.expression is ThisExpression;

class AvoidReturningThis extends LintRule {
AvoidReturningThis()
Expand Down Expand Up @@ -99,9 +96,9 @@ class _Visitor extends SimpleAstVisitor<void> {
if (body is BlockFunctionBody) {
var returnStatements = body.block
.traverseNodesInDFS(excludeCriteria: _isFunctionExpression)
.where(_isReturnStatement);
.whereType<ReturnStatement>();
if (returnStatements.isNotEmpty && returnStatements.every(_returnsThis)) {
rule.reportLintForToken(node.name2);
rule.reportLint(returnStatements.first.expression);
}
} else if (body is ExpressionFunctionBody) {
if (body.expression is ThisExpression) {
Expand Down
28 changes: 14 additions & 14 deletions test_data/rules/avoid_returning_this.dart
Expand Up @@ -8,9 +8,9 @@

class A {
int x = 0;
A badAddOne() { // LINT
A badAddOne() {
x++;
return this;
return this; // LINT
}

Object goodAddOne1() { // OK it is ok because it does not return an A type.
Expand All @@ -22,8 +22,8 @@ class A {
x++;
return this.x;
}
A getThing() { // LINT
return this;
A getThing() {
return this; // LINT
}

B doSomething() { // OK it is ok because it does not return an A type.
Expand All @@ -50,31 +50,31 @@ class B extends A{
return this;
}

B badAddOne2() { // LINT
B badAddOne2() {
x++;
return this;
return this; // LINT
}

B badOne3() { // LINT
B badOne3() {
int a() {
return 1;
}
x = a();
return this;
return this; // LINT
}

B badOne4() { // LINT
B badOne4() {
int a() => 1;
x = a();
return this;
return this; // LINT
}

B badOne5() { // LINT
B badOne5() {
final a = () {
return 1;
};
x = a();
return this;
return this; // LINT
}
}

Expand All @@ -94,8 +94,8 @@ class D implements C<D> {
return this;
}

D _m() { // LINT
return this;
D _m() {
return this; // LINT
}
}
class E implements C<E> {
Expand Down

0 comments on commit 91d8ae3

Please sign in to comment.