-
Notifications
You must be signed in to change notification settings - Fork 24
feat: add use_nearest_context rule (#190) #293
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
Open
solid-illiaaihistov
wants to merge
2
commits into
solid-software:analysis_server_migration
Choose a base branch
from
solid-illiaaihistov:issue-190-implement-use_nearest_context
base: analysis_server_migration
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,7 @@ | ||
| ## 0.3.4 | ||
|
|
||
| - Added `use_nearest_context` rule. | ||
|
|
||
| ## 0.3.3 | ||
|
|
||
| - Fix pub.dev analysis issue | ||
|
|
||
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
58 changes: 58 additions & 0 deletions
58
lib/src/lints/use_nearest_context/fixes/rename_nearest_context_parameter_fix.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,58 @@ | ||
| import 'package:analysis_server_plugin/edit/dart/correction_producer.dart'; | ||
| import 'package:analysis_server_plugin/edit/dart/dart_fix_kind_priority.dart'; | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart'; | ||
| import 'package:analyzer_plugin/utilities/fixes/fixes.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/use_nearest_context_rule.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/utils/use_nearest_context_utils.dart'; | ||
|
|
||
| /// A Quick fix for [UseNearestContextRule] rule | ||
| /// Suggests to rename the nearest BuildContext parameter | ||
| /// to the one that is being used. | ||
| class RenameNearestContextParameterFix extends ResolvedCorrectionProducer { | ||
| static const _renameParameterKind = FixKind( | ||
| 'solid_lints.fix.${UseNearestContextRule.lintName}.rename_parameter', | ||
| DartFixKindPriority.standard, | ||
| "Rename nearest BuildContext parameter", | ||
| ); | ||
|
|
||
| /// Creates a new instance of [RenameNearestContextParameterFix]. | ||
| RenameNearestContextParameterFix({required super.context}); | ||
|
|
||
| @override | ||
| FixKind get fixKind => _renameParameterKind; | ||
|
|
||
| @override | ||
| CorrectionApplicability get applicability => | ||
| CorrectionApplicability.automatically; | ||
|
|
||
| @override | ||
| Future<void> compute(ChangeBuilder builder) async { | ||
| final identifierNode = node; | ||
| if (identifierNode is! SimpleIdentifier) return; | ||
|
|
||
| // Do not offer renaming the parameter if this is an access on `this` | ||
| // or `super`. | ||
| final parent = identifierNode.parent; | ||
| if (parent is PropertyAccess) { | ||
| var target = parent.target; | ||
| while (target is ParenthesizedExpression) { | ||
| target = target.expression; | ||
| } | ||
| if (target is ThisExpression || target is SuperExpression) return; | ||
| } | ||
|
|
||
| final closestBuildContext = findClosestBuildContext(identifierNode); | ||
| if (closestBuildContext == null) return; | ||
|
|
||
| final parameterName = closestBuildContext.name; | ||
| if (parameterName == null) return; | ||
|
|
||
| await builder.addDartFileEdit(file, (builder) { | ||
| builder.addSimpleReplacement( | ||
| parameterName.sourceRange, | ||
| identifierNode.name, | ||
| ); | ||
| }); | ||
| } | ||
| } |
68 changes: 68 additions & 0 deletions
68
lib/src/lints/use_nearest_context/fixes/replace_with_nearest_context_parameter_fix.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,68 @@ | ||
| import 'package:analysis_server_plugin/edit/dart/correction_producer.dart'; | ||
| import 'package:analysis_server_plugin/edit/dart/dart_fix_kind_priority.dart'; | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart'; | ||
| import 'package:analyzer_plugin/utilities/fixes/fixes.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/use_nearest_context_rule.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/utils/use_nearest_context_utils.dart'; | ||
|
|
||
| /// A Quick fix for [UseNearestContextRule] rule | ||
| /// Suggests to replace the outer BuildContext expression | ||
| /// with the nearest available parameter. | ||
| class ReplaceWithNearestContextParameterFix extends ResolvedCorrectionProducer { | ||
| static const _replaceExpressionKind = FixKind( | ||
| 'solid_lints.fix.${UseNearestContextRule.lintName}.replace_expression', | ||
| DartFixKindPriority.standard, | ||
| "Replace with nearest BuildContext parameter", | ||
| ); | ||
|
|
||
| /// Creates a new instance of [ReplaceWithNearestContextParameterFix]. | ||
| ReplaceWithNearestContextParameterFix({required super.context}); | ||
|
|
||
| @override | ||
| FixKind get fixKind => _replaceExpressionKind; | ||
|
|
||
| @override | ||
| CorrectionApplicability get applicability => | ||
| CorrectionApplicability.automatically; | ||
|
|
||
| @override | ||
| Future<void> compute(ChangeBuilder builder) async { | ||
| final errorNode = node; | ||
|
|
||
| final closestBuildContext = findClosestBuildContext(errorNode); | ||
| if (closestBuildContext == null) return; | ||
|
|
||
| final parameterName = closestBuildContext.name?.lexeme; | ||
| if (parameterName == null) return; | ||
|
|
||
| if (errorNode is ThisExpression) { | ||
| await builder.addDartFileEdit(file, (builder) { | ||
| builder.addSimpleReplacement( | ||
| errorNode.sourceRange, | ||
| parameterName, | ||
| ); | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| if (errorNode is SimpleIdentifier) { | ||
| final parent = errorNode.parent; | ||
| if (parent is PropertyAccess) { | ||
| var target = parent.target; | ||
| while (target is ParenthesizedExpression) { | ||
| target = target.expression; | ||
| } | ||
| if (target is ThisExpression || target is SuperExpression) { | ||
| await builder.addDartFileEdit(file, (builder) { | ||
| builder.addSimpleReplacement( | ||
| parent.sourceRange, | ||
| parameterName, | ||
| ); | ||
| }); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
|
solid-illiaaihistov marked this conversation as resolved.
|
||
| } | ||
| } | ||
82 changes: 82 additions & 0 deletions
82
lib/src/lints/use_nearest_context/use_nearest_context_rule.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,82 @@ | ||
| import 'package:analyzer/analysis_rule/analysis_rule.dart'; | ||
| import 'package:analyzer/analysis_rule/rule_context.dart'; | ||
| import 'package:analyzer/analysis_rule/rule_visitor_registry.dart'; | ||
| import 'package:analyzer/error/error.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/visitors/use_nearest_context_visitor.dart'; | ||
|
|
||
| /// A rule which checks that we use BuildContext from the nearest available | ||
| /// scope. | ||
| /// | ||
| /// ### Example: | ||
| /// #### BAD: | ||
| /// ```dart | ||
| /// class SomeWidget extends StatefulWidget { | ||
| /// ... | ||
| /// } | ||
| /// | ||
| /// class _SomeWidgetState extends State<SomeWidget> { | ||
| /// ... | ||
| /// void _showDialog() { | ||
| /// showModalBottomSheet( | ||
| /// context: context, | ||
| /// builder: (BuildContext _) { | ||
| /// final someProvider = context.watch<SomeProvider>(); // LINT, BuildContext is used not from the nearest available scope | ||
| /// | ||
| /// return const SizedBox.shrink(); | ||
| /// }, | ||
| /// ); | ||
| /// } | ||
| /// } | ||
| /// ``` | ||
| /// #### GOOD: | ||
| /// ```dart | ||
| /// class SomeWidget extends StatefulWidget { | ||
| /// ... | ||
| /// } | ||
| /// | ||
| /// class _SomeWidgetState extends State<SomeWidget> { | ||
| /// ... | ||
| /// void _showDialog() { | ||
| /// showModalBottomSheet( | ||
| /// context: context, | ||
| /// builder: (BuildContext context) | ||
| /// final someProvider = context.watch<SomeProvider>(); // OK | ||
| /// | ||
| /// return const SizedBox.shrink(); | ||
| /// }, | ||
| /// ); | ||
| /// } | ||
| /// } | ||
| /// ``` | ||
| /// | ||
| class UseNearestContextRule extends AnalysisRule { | ||
| /// This lint rule represents the error if BuildContext is used not from the | ||
| /// nearest available scope | ||
| static const lintName = 'use_nearest_context'; | ||
|
|
||
| /// The code to report for a violation | ||
| static const LintCode code = LintCode( | ||
| lintName, | ||
| 'Use the nearest BuildContext parameter instead of the outer one.', | ||
| ); | ||
|
|
||
| /// Creates a new instance of [UseNearestContextRule]. | ||
| UseNearestContextRule() | ||
| : super( | ||
| name: lintName, | ||
| description: code.problemMessage, | ||
| ); | ||
|
|
||
| @override | ||
| LintCode get diagnosticCode => code; | ||
|
|
||
| @override | ||
| void registerNodeProcessors( | ||
| RuleVisitorRegistry registry, | ||
| RuleContext context, | ||
| ) { | ||
| final visitor = UseNearestContextVisitor(this); | ||
| registry.addSimpleIdentifier(this, visitor); | ||
| registry.addThisExpression(this, visitor); | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
lib/src/lints/use_nearest_context/utils/use_nearest_context_utils.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,23 @@ | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:solid_lints/src/utils/types_utils.dart'; | ||
|
|
||
| /// Finds the closest BuildContext parameter in the AST parent chain of [node]. | ||
| SimpleFormalParameter? findClosestBuildContext(AstNode node) { | ||
| AstNode? current = node.parent; | ||
|
|
||
| while (current != null) { | ||
| if (current is FunctionExpression) { | ||
| final functionParams = current.parameters?.parameters ?? []; | ||
| for (final param in functionParams) { | ||
| final actualParam = | ||
| param is DefaultFormalParameter ? param.parameter : param; | ||
| if (actualParam is SimpleFormalParameter && | ||
| isBuildContext(actualParam.declaredFragment?.element.type)) { | ||
| return actualParam; | ||
| } | ||
| } | ||
| } | ||
| current = current.parent; | ||
| } | ||
| return null; | ||
| } |
74 changes: 74 additions & 0 deletions
74
lib/src/lints/use_nearest_context/visitors/use_nearest_context_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,74 @@ | ||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer/dart/ast/visitor.dart'; | ||
| import 'package:analyzer/dart/element/element.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/use_nearest_context_rule.dart'; | ||
| import 'package:solid_lints/src/lints/use_nearest_context/utils/use_nearest_context_utils.dart'; | ||
| import 'package:solid_lints/src/utils/types_utils.dart'; | ||
|
|
||
| /// A visitor for [UseNearestContextRule]. | ||
| class UseNearestContextVisitor extends SimpleAstVisitor<void> { | ||
| final UseNearestContextRule _rule; | ||
|
|
||
| /// Creates a new instance of [UseNearestContextVisitor]. | ||
| UseNearestContextVisitor(this._rule); | ||
|
|
||
| @override | ||
| void visitSimpleIdentifier(SimpleIdentifier node) { | ||
| if (!isBuildContext(node.staticType)) return; | ||
| if (_isPropertyOfOtherObject(node)) return; | ||
|
|
||
| final closestBuildContext = findClosestBuildContext(node); | ||
| if (closestBuildContext == null) return; | ||
| if (closestBuildContext.name?.lexeme != node.name) { | ||
| if (_isDeclaredInNearestScope(node, closestBuildContext)) return; | ||
|
|
||
| _rule.reportAtNode(node); | ||
| } | ||
| } | ||
|
|
||
| @override | ||
| void visitThisExpression(ThisExpression node) { | ||
| if (!isBuildContext(node.staticType)) return; | ||
|
|
||
| final closestBuildContext = findClosestBuildContext(node); | ||
| if (closestBuildContext == null) return; | ||
|
|
||
| _rule.reportAtNode(node); | ||
| } | ||
|
|
||
| /// Returns `true` if [node] is a property accessed on another object | ||
| /// (e.g. `state.context`), but not on `this` (e.g. `this.context`). | ||
| bool _isPropertyOfOtherObject(SimpleIdentifier node) { | ||
| final parent = node.parent; | ||
| if (parent is PrefixedIdentifier && node == parent.identifier) { | ||
| return true; | ||
| } | ||
| if (parent is PropertyAccess && node == parent.propertyName) { | ||
| var target = parent.target; | ||
| while (target is ParenthesizedExpression) { | ||
| target = target.expression; | ||
| } | ||
| return target is! ThisExpression && target is! SuperExpression; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /// Returns `true` if [node] refers to a variable declared inside the body | ||
| /// of the function that owns [closestParam] (i.e. a local variable | ||
| /// in the same scope, like `final localCtx = innerContext;`). | ||
| bool _isDeclaredInNearestScope( | ||
| SimpleIdentifier node, | ||
| SimpleFormalParameter closestParam, | ||
| ) { | ||
| final element = node.element; | ||
| if (element is! LocalVariableElement) return false; | ||
|
|
||
| final nearestFunction = closestParam.parent?.parent; | ||
| if (nearestFunction is! FunctionExpression) return false; | ||
|
|
||
| final body = nearestFunction.body; | ||
| final declOffset = element.firstFragment.nameOffset; | ||
| if (declOffset == null) return false; | ||
| return declOffset >= body.offset && declOffset < body.end; | ||
|
solid-illiaaihistov marked this conversation as resolved.
solid-illiaaihistov marked this conversation as resolved.
|
||
| } | ||
| } | ||
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
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.