-
Notifications
You must be signed in to change notification settings - Fork 24
feat: enhance prefer_early_return rule to support loops and parameters #351
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
Merged
solid-illiaaihistov
merged 3 commits into
solid-software:master
from
solid-illiaaihistov:343-extend-prefer_early_return
Aug 28, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
lib/src/lints/prefer_early_return/models/prefer_early_return_parameters.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /// A data model class that represents the "prefer early return" | ||
| /// input parameters. | ||
| class PreferEarlyReturnParameters { | ||
| static const _maximumStatementsConfig = 'maximum_statements'; | ||
| static const _ignoreIfCaseConfig = 'ignore_if_case'; | ||
|
|
||
| static const _defaultMaximumStatements = 1; | ||
| static const _defaultIgnoreIfCase = true; | ||
|
|
||
| /// The maximum number of statements allowed inside an `if` block before | ||
| /// triggering the lint. If the number of statements does not exceed this | ||
| /// threshold, the analysis is skipped. | ||
| final int maximumStatements; | ||
|
|
||
| /// Whether to ignore `if-case` pattern matching statements. | ||
| final bool ignoreIfCase; | ||
|
|
||
| /// Constructor for [PreferEarlyReturnParameters] model. | ||
| const PreferEarlyReturnParameters({ | ||
| required this.maximumStatements, | ||
| required this.ignoreIfCase, | ||
| }); | ||
|
|
||
| /// Empty [PreferEarlyReturnParameters] model with default values. | ||
| factory PreferEarlyReturnParameters.empty() => | ||
| const PreferEarlyReturnParameters( | ||
| maximumStatements: _defaultMaximumStatements, | ||
| ignoreIfCase: _defaultIgnoreIfCase, | ||
| ); | ||
|
|
||
| /// Method for creating [PreferEarlyReturnParameters] from json data. | ||
| factory PreferEarlyReturnParameters.fromJson( | ||
| Map<String, Object?> json, | ||
| ) => PreferEarlyReturnParameters( | ||
| maximumStatements: | ||
| json[_maximumStatementsConfig] as int? ?? _defaultMaximumStatements, | ||
| ignoreIfCase: json[_ignoreIfCaseConfig] as bool? ?? _defaultIgnoreIfCase, | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 57 additions & 0 deletions
57
lib/src/lints/prefer_early_return/visitors/early_return_exit_visitor.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer/dart/ast/visitor.dart'; | ||
|
|
||
| /// AST visitor that checks if a statement contains an early exit | ||
| /// (return, throw, or loop break/continue) respecting scope boundaries. | ||
| class EarlyReturnExitVisitor extends RecursiveAstVisitor<void> { | ||
| final Statement _root; | ||
| bool _hasExit = false; | ||
|
|
||
| EarlyReturnExitVisitor._(this._root); | ||
|
|
||
| /// Checks whether [node] contains any early exit statement. | ||
| static bool hasExitIn(Statement node) { | ||
| final visitor = EarlyReturnExitVisitor._(node); | ||
| node.accept(visitor); | ||
| return visitor._hasExit; | ||
| } | ||
|
|
||
| @override | ||
| void visitReturnStatement(ReturnStatement node) => _hasExit = true; | ||
|
|
||
| @override | ||
| void visitThrowExpression(ThrowExpression node) => _hasExit = true; | ||
|
|
||
| @override | ||
| void visitRethrowExpression(RethrowExpression node) => _hasExit = true; | ||
|
|
||
| @override | ||
| void visitBreakStatement(BreakStatement node) => _checkExit(node.target); | ||
|
|
||
| @override | ||
| void visitContinueStatement(ContinueStatement node) => | ||
| _checkExit(node.target); | ||
|
|
||
| @override | ||
| void visitFunctionExpression(FunctionExpression node) {} | ||
|
|
||
| @override | ||
| void visitFunctionDeclaration(FunctionDeclaration node) {} | ||
|
|
||
| bool _isDescendantOfRoot(AstNode target) { | ||
| AstNode? current = target; | ||
| while (current != null) { | ||
| if (identical(current, _root)) { | ||
| return true; | ||
| } | ||
| current = current.parent; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| void _checkExit(AstNode? target) { | ||
| if (target case final target? when !_isDescendantOfRoot(target)) { | ||
| _hasExit = true; | ||
| } | ||
| } | ||
| } |
102 changes: 55 additions & 47 deletions
102
lib/src/lints/prefer_early_return/visitors/prefer_early_return_visitor.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,84 +1,92 @@ | ||
| import 'package:analyzer/analysis_rule/rule_context.dart'; | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer/dart/ast/visitor.dart'; | ||
| import 'package:solid_lints/src/lints/prefer_early_return/models/prefer_early_return_parameters.dart'; | ||
| import 'package:solid_lints/src/lints/prefer_early_return/prefer_early_return_rule.dart'; | ||
| import 'package:solid_lints/src/lints/prefer_early_return/visitors/return_statement_visitor.dart'; | ||
| import 'package:solid_lints/src/lints/prefer_early_return/visitors/throw_expression_visitor.dart'; | ||
| import 'package:solid_lints/src/lints/prefer_early_return/visitors/early_return_exit_visitor.dart'; | ||
|
|
||
| /// Visitor for [PreferEarlyReturnRule]. | ||
| class PreferEarlyReturnVisitor extends RecursiveAstVisitor<void> { | ||
| class PreferEarlyReturnVisitor extends SimpleAstVisitor<void> { | ||
| /// The rule associated with the visitor. | ||
| final PreferEarlyReturnRule rule; | ||
|
|
||
| /// The context associated with the visitor. | ||
| final RuleContext context; | ||
|
|
||
| /// The parameters associated with the rule. | ||
| final PreferEarlyReturnParameters parameters; | ||
|
|
||
| /// Constructor for [PreferEarlyReturnVisitor]. | ||
| PreferEarlyReturnVisitor({ | ||
| required this.rule, | ||
| required this.context, | ||
| required this.parameters, | ||
| }); | ||
|
|
||
| @override | ||
| void visitBlockFunctionBody(BlockFunctionBody node) { | ||
| super.visitBlockFunctionBody(node); | ||
| void visitBlockFunctionBody(BlockFunctionBody node) => | ||
| _checkStatements(node.block.statements, isLoop: false); | ||
|
|
||
| if (node.block.statements.isEmpty) return; | ||
| @override | ||
| void visitForStatement(ForStatement node) => _checkLoopBody(node.body); | ||
|
|
||
| final (ifStatements, nextStatement) = _getIfStatementsAndNextStatement( | ||
| node, | ||
| ); | ||
| if (ifStatements.isEmpty) return; | ||
| @override | ||
| void visitWhileStatement(WhileStatement node) => _checkLoopBody(node.body); | ||
|
|
||
| @override | ||
| void visitDoStatement(DoStatement node) => _checkLoopBody(node.body); | ||
|
|
||
| // limit visitor to only work with functions | ||
| // that don't have a return statement or the return statement is empty | ||
| final nextStatementIsEmptyReturn = | ||
| nextStatement is ReturnStatement && nextStatement.expression == null; | ||
| final nextStatementIsNull = nextStatement == null; | ||
| void _checkLoopBody(Statement body) { | ||
| final List<Statement> statements = switch (body) { | ||
| Block(:final statements) => statements, | ||
| IfStatement() => [body], | ||
| _ => const [], | ||
| }; | ||
|
|
||
| if (!nextStatementIsEmptyReturn && !nextStatementIsNull) return; | ||
| if (statements.isNotEmpty) { | ||
| _checkStatements(statements, isLoop: true); | ||
| } | ||
| } | ||
|
|
||
| final lastIf = ifStatements.last; | ||
| void _checkStatements( | ||
| List<Statement> statements, { | ||
| required bool isLoop, | ||
| }) { | ||
| final (leading, lastIf) = switch (statements) { | ||
| [...final leading, IfStatement lastIf] => (leading, lastIf), | ||
| [...final leading, IfStatement lastIf, ContinueStatement(label: null)] | ||
| when isLoop => | ||
| (leading, lastIf), | ||
| [...final leading, IfStatement lastIf, ReturnStatement(expression: null)] | ||
| when !isLoop => | ||
| (leading, lastIf), | ||
| _ => (null, null), | ||
| }; | ||
|
|
||
| if (lastIf case IfStatement(elseStatement: Statement())) return; | ||
| if (_hasReturnStatement(lastIf) || _hasThrowExpression(lastIf)) return; | ||
| if (lastIf == null || !leading!.every((s) => s is IfStatement)) return; | ||
| if (!_shouldReport(lastIf)) return; | ||
|
|
||
| context.currentUnit?.diagnosticReporter.atNode( | ||
| lastIf, | ||
| rule.diagnosticCode, | ||
| ); | ||
| } | ||
|
|
||
| // returns a list of if statements at the start of the function | ||
| // and the next statement after it | ||
| // examples: | ||
| // [if, if, if, return] -> ([if, if, if], return) | ||
| // [if, if, if, _doSomething, return] -> ([if, if, if], _doSomething) | ||
| // [if, if, if] -> ([if, if, if], null) | ||
| (List<IfStatement>, Statement?) _getIfStatementsAndNextStatement( | ||
| BlockFunctionBody body, | ||
| ) { | ||
| final List<IfStatement> ifStatements = []; | ||
| for (final statement in body.block.statements) { | ||
| if (statement is IfStatement) { | ||
| ifStatements.add(statement); | ||
| } else { | ||
| return (ifStatements, statement); | ||
| } | ||
| } | ||
| bool _shouldReport(IfStatement ifStatement) { | ||
| final IfStatement(:thenStatement, :elseStatement, :caseClause) = | ||
| ifStatement; | ||
|
|
||
| return (ifStatements, null); | ||
| } | ||
| if (elseStatement != null || | ||
| (parameters.ignoreIfCase && caseClause != null)) { | ||
| return false; | ||
| } | ||
|
|
||
| bool _hasReturnStatement(Statement node) { | ||
| final visitor = ReturnStatementVisitor(); | ||
| node.accept(visitor); | ||
| return visitor.nodes.isNotEmpty; | ||
| } | ||
| final statementsCount = switch (thenStatement) { | ||
| Block(:final statements) => statements.length, | ||
| _ => 1, | ||
| }; | ||
|
|
||
| bool _hasThrowExpression(Statement node) { | ||
| final visitor = ThrowExpressionVisitor(); | ||
| node.accept(visitor); | ||
| return visitor.nodes.isNotEmpty; | ||
| return statementsCount > parameters.maximumStatements && | ||
| !EarlyReturnExitVisitor.hasExitIn(thenStatement); | ||
| } | ||
| } |
16 changes: 0 additions & 16 deletions
16
lib/src/lints/prefer_early_return/visitors/return_statement_visitor.dart
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.