-
Notifications
You must be signed in to change notification settings - Fork 24
Add use_nearest_context lint rule (#190) #288
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
Closed
solid-illiaaihistov
wants to merge
2
commits into
solid-software:master
from
solid-illiaaihistov:issue-190-implement-use-nearest-context
Closed
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
64 changes: 64 additions & 0 deletions
64
lib/src/lints/use_nearest_context/fixes/use_nearest_context_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,64 @@ | ||
| part of '../use_nearest_context_rule.dart'; | ||
|
|
||
| /// A Quick fix for `use_nearest_context` rule | ||
| /// Suggests to renaming the nearest BuildContext variable | ||
| /// to the one that is being used | ||
| class _UseNearestContextFix extends DartFix { | ||
| static const _replaceComment = "Rename nearest BuildContext parameter"; | ||
|
|
||
| final Expando<StatementInfo> _diagnosticsInfoExpando; | ||
|
|
||
| _UseNearestContextFix(this._diagnosticsInfoExpando); | ||
|
|
||
| @override | ||
| void run( | ||
| CustomLintResolver resolver, | ||
| ChangeReporter reporter, | ||
| CustomLintContext context, | ||
| Diagnostic diagnostic, | ||
| List<Diagnostic> others, | ||
| ) { | ||
| final statementInfo = _diagnosticsInfoExpando[diagnostic]; | ||
| if (statementInfo == null) return; | ||
| final parameterName = statementInfo.parameter.name; | ||
| if (parameterName == null) return; | ||
|
|
||
| _addReplacement(reporter, parameterName, statementInfo.name); | ||
| } | ||
|
|
||
| void _addReplacement( | ||
| ChangeReporter reporter, | ||
| Token? token, | ||
| String correction, | ||
| ) { | ||
| if (token == null) return; | ||
| final changeBuilder = reporter.createChangeBuilder( | ||
| message: _replaceComment, | ||
| priority: 1, | ||
| ); | ||
|
|
||
| changeBuilder.addDartFileEdit((builder) { | ||
| builder.addSimpleReplacement( | ||
| token.sourceRange, | ||
| correction, | ||
| ); | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /// Data class that holds info required for the [_UseNearestContextFix]. | ||
| class StatementInfo { | ||
| /// Creates instance of a [StatementInfo]. | ||
| const StatementInfo({ | ||
| required this.name, | ||
| required this.parameter, | ||
| }); | ||
|
|
||
| /// The name of the outer BuildContext variable that was used | ||
| /// instead of the nearest one. | ||
| final String name; | ||
|
|
||
| /// The nearest [SimpleFormalParameter] of type BuildContext | ||
| /// that should have been used instead. | ||
| final SimpleFormalParameter parameter; | ||
| } |
160 changes: 160 additions & 0 deletions
160
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,160 @@ | ||
| // ignore_for_file: avoid_print, lines_longer_than_80_chars | ||
|
|
||
| import 'package:analyzer/dart/ast/ast.dart'; | ||
| import 'package:analyzer/dart/ast/token.dart'; | ||
| import 'package:analyzer/dart/element/element.dart'; | ||
| import 'package:analyzer/diagnostic/diagnostic.dart'; | ||
| import 'package:analyzer/error/listener.dart'; | ||
| import 'package:custom_lint_builder/custom_lint_builder.dart'; | ||
| import 'package:solid_lints/src/models/rule_config.dart'; | ||
| import 'package:solid_lints/src/models/solid_lint_rule.dart'; | ||
| import 'package:solid_lints/src/utils/types_utils.dart'; | ||
|
|
||
| part 'fixes/use_nearest_context_fix.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 SolidLintRule { | ||
| /// This lint rule represents the error if BuildContext is used not from the | ||
| /// nearest available scope | ||
| static const lintName = 'use_nearest_context'; | ||
|
|
||
| final _diagnosticsInfoExpando = Expando<StatementInfo>(); | ||
|
|
||
| UseNearestContextRule._(super.rule); | ||
|
|
||
| /// Creates a new instance of [UseNearestContextRule] | ||
| /// based on the lint configuration. | ||
| factory UseNearestContextRule.createRule(CustomLintConfigs configs) { | ||
| final rule = RuleConfig( | ||
| configs: configs, | ||
| name: lintName, | ||
| problemMessage: (value) => | ||
| 'Use the nearest BuildContext parameter instead of the outer one.', | ||
| ); | ||
|
|
||
| return UseNearestContextRule._(rule); | ||
| } | ||
|
|
||
| @override | ||
| void run( | ||
| CustomLintResolver resolver, | ||
| DiagnosticReporter reporter, | ||
| CustomLintContext context, | ||
| ) { | ||
| context.registry.addSimpleIdentifier((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; | ||
|
|
||
| final diagnostic = reporter.atNode(node, code); | ||
| _diagnosticsInfoExpando[diagnostic] = StatementInfo( | ||
| name: node.name, | ||
| parameter: closestBuildContext, | ||
| ); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| /// 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) { | ||
| return parent.target is! ThisExpression; | ||
| } | ||
| 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.
|
||
| } | ||
|
|
||
| SimpleFormalParameter? _findClosestBuildContext(SimpleIdentifier 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; | ||
|
solid-illiaaihistov marked this conversation as resolved.
|
||
| } | ||
| } | ||
| } | ||
| current = current.parent; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @override | ||
| List<Fix> getFixes() => [_UseNearestContextFix(_diagnosticsInfoExpando)]; | ||
| } | ||
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 |
|---|---|---|
|
|
@@ -90,3 +90,4 @@ custom_lint: | |
| - nullable | ||
| - default | ||
| - avoid_unnecessary_return_variable | ||
| - use_nearest_context | ||
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.