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
4 changes: 4 additions & 0 deletions CHANGELOG.md
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
Expand Down
14 changes: 14 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ import 'package:solid_lints/src/lints/avoid_returning_widgets/models/avoid_retur
import 'package:solid_lints/src/lints/double_literal_format/double_literal_format_rule.dart';
import 'package:solid_lints/src/lints/double_literal_format/fixes/double_literal_format_fix.dart';
import 'package:solid_lints/src/lints/proper_super_calls/proper_super_calls_rule.dart';
import 'package:solid_lints/src/lints/use_nearest_context/fixes/rename_nearest_context_parameter_fix.dart';
import 'package:solid_lints/src/lints/use_nearest_context/fixes/replace_with_nearest_context_parameter_fix.dart';
import 'package:solid_lints/src/lints/use_nearest_context/use_nearest_context_rule.dart';

/// The entry point for the Solid Lints analyser server plugin.
///
Expand Down Expand Up @@ -42,6 +45,7 @@ class SolidLintsPlugin extends Plugin {
analysisOptionsLoader: analysisLoader,
parametersParser: AvoidReturningWidgetsParameters.fromJson,
),
UseNearestContextRule(),
];

for (final lintRule in lintRules) {
Expand All @@ -56,5 +60,15 @@ class SolidLintsPlugin extends Plugin {
AvoidFinalWithGetterRule.code,
AvoidFinalWithGetterFix.new,
);

registry.registerFixForRule(
UseNearestContextRule.code,
RenameNearestContextParameterFix.new,
);

registry.registerFixForRule(
UseNearestContextRule.code,
ReplaceWithNearestContextParameterFix.new,
);
}
}
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,
);
});
}
}
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;
}
}
}
Comment thread
solid-illiaaihistov marked this conversation as resolved.
Comment thread
solid-illiaaihistov marked this conversation as resolved.
}
}
82 changes: 82 additions & 0 deletions lib/src/lints/use_nearest_context/use_nearest_context_rule.dart
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);
}
}
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;
}
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);
}
Comment on lines +22 to +26

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (closestBuildContext.name?.lexeme != node.name) {
if (_isDeclaredInNearestScope(node, closestBuildContext)) return;
_rule.reportAtNode(node);
}
if (closestBuildContext.name?.lexeme == node.name) return;
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;
Comment thread
solid-illiaaihistov marked this conversation as resolved.
Comment thread
solid-illiaaihistov marked this conversation as resolved.
}
}
7 changes: 5 additions & 2 deletions lib/src/utils/types_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,11 @@ bool isRowWidget(DartType? type) => type?.getDisplayString() == 'Row';

bool isPaddingWidget(DartType? type) => type?.getDisplayString() == 'Padding';

bool isBuildContext(DartType? type) =>
type?.getDisplayString() == 'BuildContext';
bool isBuildContext(DartType? type) {
if (type == null) return false;
final displayString = type.getDisplayString();
return displayString == 'BuildContext' || displayString == 'BuildContext?';
}

bool isGameWidget(DartType? type) => type?.getDisplayString() == 'GameWidget';

Expand Down
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: solid_lints
description:
Lints for Dart and Flutter based on software industry standards and best
practices.
version: 0.3.3
version: 0.3.4
homepage: https://github.com/solid-software/solid_lints/
documentation: https://solid-software.github.io/solid_lints/docs/intro
topics: [lints, linter, lint, analysis, analyzer]
Expand Down
Loading
Loading