Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@ class AvoidUnnecessaryReturnVariableVisitor extends SimpleAstVisitor<void> {

@override
void visitReturnStatement(ReturnStatement node) {
final expr = node.expression;
final expr = node.expression?.unParenthesized;
if (expr is! SimpleIdentifier) return;

final element = expr.element;
if (element is! LocalVariableElement) return;

if (!element.isFinal && !element.isConst) return;

final block = node.parent;
//get enclosing block function body
final block = node.thisOrAncestorOfType<BlockFunctionBody>()?.block;
if (block == null) return;

final returnVariableUsageVisitor = ReturnVariableUsageVisitor(
Expand All @@ -34,16 +35,18 @@ class AvoidUnnecessaryReturnVariableVisitor extends SimpleAstVisitor<void> {
block.visitChildren(returnVariableUsageVisitor);
if (!returnVariableUsageVisitor.hasBadStatementCount) return;

//check if declaration statement is found
final declaration = returnVariableUsageVisitor.variableDeclaration;
if (declaration == null) return;

//it is 100% bad if return statement follows declaration
if (!returnVariableUsageVisitor.foundTokensBetweenDeclarationAndReturn) {
_rule.reportAtNode(node);
return;
}

final declaration = returnVariableUsageVisitor.variableDeclaration;

//check if immutable
final initializer = declaration?.initializer;
final initializer = declaration.initializer;
if (initializer == null) return;

if (!_isExpressionImmutable(initializer)) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,44 @@ void _doNothing() {}
[lint(304, 14)],
);
}

void test_does_not_report_if_return_is_cached_nested_block() async {
await assertNoDiagnostics(r'''
Future<String?> testAvoidUnnecessaryReturnVariableNestedBlock() async {
final cached = 'cached';
if (cached.isNotEmpty) {
// Should NOT trigger the avoid_unnecessary_return_variable lint
return cached;
}
return null;
}
''');
}

void test_reports_if_return_is_cached_and_only_returned_nested_block() async {
await assertDiagnostics(
r'''
int test(bool b) {
final a = 3;
if (b) {
return a;
}
return 0;
}
''',
[lint(49, 9)],
);
}

void test_reports_if_return_in_parentheses() async {
await assertDiagnostics(
r'''
int test() {
final a = 3;
return (a);
}
''',
[lint(30, 11)],
);
}
}
Loading