Skip to content
This repository was archived by the owner on Jul 16, 2023. It is now read-only.

feat: add strict config option to avoid-collection-methods-with-unrelated-types #1111

Merged
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

* feat: add `strict` config option to [`avoid-collection-methods-with-unrelated-types`](https://dartcodemetrics.dev/docs/rules/common/avoid-collection-methods-with-unrelated-types).
* fix: support function expression invocations for [`prefer-moving-to-variable`](https://dartcodemetrics.dev/docs/rules/common/prefer-moving-to-variable).
* feat: support ignoring regular comments for [`format-comment`](https://dartcodemetrics.dev/docs/rules/common/format-comment).

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,20 @@ import '../../../models/severity.dart';
import '../../models/common_rule.dart';
import '../../rule_utils.dart';

part 'config_parser.dart';
part 'visitor.dart';

class AvoidCollectionMethodsWithUnrelatedTypesRule extends CommonRule {
static const String ruleId = 'avoid-collection-methods-with-unrelated-types';

static const _warning = 'Avoid collection methods with unrelated types.';

final bool _isStrictMode;

AvoidCollectionMethodsWithUnrelatedTypesRule([
Map<String, Object> config = const {},
]) : super(
]) : _isStrictMode = _ConfigParser.parseIsStrictMode(config),
super(
id: ruleId,
severity: readSeverity(config, Severity.warning),
excludes: readExcludes(config),
Expand All @@ -34,7 +38,7 @@ class AvoidCollectionMethodsWithUnrelatedTypesRule extends CommonRule {

@override
Iterable<Issue> check(InternalResolvedUnitResult source) {
final visitor = _Visitor();
final visitor = _Visitor(_isStrictMode);

source.unit.visitChildren(visitor);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
part of 'avoid_collection_methods_with_unrelated_types_rule.dart';

class _ConfigParser {
static const _strictConfig = 'strict';

static bool parseIsStrictMode(Map<String, Object> config) =>
config[_strictConfig] == null || config[_strictConfig] == true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ part of 'avoid_collection_methods_with_unrelated_types_rule.dart';
class _Visitor extends RecursiveAstVisitor<void> {
final _expressions = <Expression>[];

final bool _isStrictMode;

Iterable<Expression> get expressions => _expressions;

// ignore: avoid_positional_boolean_parameters
_Visitor(this._isStrictMode);

// for `operator []` and `operator []=`
@override
void visitIndexExpression(IndexExpression node) {
Expand Down Expand Up @@ -66,13 +71,20 @@ class _Visitor extends RecursiveAstVisitor<void> {
) {
if (parentElement != null &&
childType != null &&
childType.asInstanceOf(parentElement.element) == null &&
(_isNotInstance(childType, parentElement) &&
_isNotDynamic(childType)) &&
!(parentElement.type.nullabilitySuffix == NullabilitySuffix.question &&
childType.isDartCoreNull)) {
_expressions.add(node);
}
}

bool _isNotInstance(DartType type, _TypedClassElement parentElement) =>
type.asInstanceOf(parentElement.element) == null;

bool _isNotDynamic(DartType type) =>
_isStrictMode || !(type.isDynamic || type.isDartCoreObject);

List<_TypedClassElement>? _getMapTypeElement(DartType? type) =>
_getTypeArgElements(getSupertypeMap(type));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const _examplePath =
'avoid_collection_methods_with_unrelated_types/examples/example.dart';
const _nullableExamplePath =
'avoid_collection_methods_with_unrelated_types/examples/nullable_example.dart';
const _dynamicExamplePath =
'avoid_collection_methods_with_unrelated_types/examples/dynamic_example.dart';

void main() {
group('AvoidCollectionMethodsWithUnrelatedTypesRule', () {
Expand Down Expand Up @@ -161,5 +163,33 @@ void main() {
],
);
});

test('reports about found issues for dynamic keys', () async {
final unit = await RuleTestHelper.resolveFromFile(_dynamicExamplePath);
final issues = AvoidCollectionMethodsWithUnrelatedTypesRule().check(unit);

RuleTestHelper.verifyIssues(
issues: issues,
startLines: [6, 13],
startColumns: [5, 5],
locationTexts: [
'regularMap[key]',
'regularMap[key]',
],
messages: [
'Avoid collection methods with unrelated types.',
'Avoid collection methods with unrelated types.',
],
);
});

test('reports no issues for dynamic keys if not in strict mode', () async {
final unit = await RuleTestHelper.resolveFromFile(_dynamicExamplePath);
final issues = AvoidCollectionMethodsWithUnrelatedTypesRule(const {
'strict': false,
}).check(unit);

RuleTestHelper.verifyNoIssues(issues);
});
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
void main() {
{
dynamic key = 1;

final regularMap = Map<int, String>();
regularMap[key] = "value"; // LINT
}

{
Object? key = 1;

final regularMap = Map<int, String>();
regularMap[key] = "value"; // LINT
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,19 @@ Related: Dart's built-in `list_remove_unrelated_type` and `iterable_contains_unr

:::

Use `strict` configuration (default is `true`), if you want `dynamic` or `Object` type keys to not trigger the warning.

### ⚙️ Config example {#config-example}

```yaml
dart_code_metrics:
...
rules:
...
- avoid-collection-methods-with-unrelated-types:
strict: false
```

### Example {#example}

**❌ Bad:**
Expand Down