Skip to content
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

add lint function_expression_with_incorrect_types #2530

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions example/all.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ linter:
- exhaustive_cases
- file_names
- flutter_style_todos
- function_expression_with_incorrect_types
- hash_and_equals
- implementation_imports
- invariant_booleans
Expand Down
2 changes: 2 additions & 0 deletions lib/src/rules.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ import 'rules/empty_statements.dart';
import 'rules/exhaustive_cases.dart';
import 'rules/file_names.dart';
import 'rules/flutter_style_todos.dart';
import 'rules/function_expression_with_incorrect_types.dart';
import 'rules/hash_and_equals.dart';
import 'rules/implementation_imports.dart';
import 'rules/invariant_booleans.dart';
Expand Down Expand Up @@ -266,6 +267,7 @@ void registerLintRules({bool inTestMode = false}) {
..register(ExhaustiveCases())
..register(FileNames())
..register(FlutterStyleTodos())
..register(FunctionExpressionWithIncorrectTypes())
..register(HashAndEquals())
..register(ImplementationImports())
..register(InvariantBooleans())
Expand Down
125 changes: 125 additions & 0 deletions lib/src/rules/function_expression_with_incorrect_types.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:collection/collection.dart';

import '../analyzer.dart';

const _desc =
r'Use the parameter types expected by the target in function expression.';

const _details = r'''

Use the parameter types expected by the target in function expression.

**BAD:**
```
f(void Function(int a) p) {}

f((int? a) {});
f((num a) {});
```

**GOOD:**
```
f(void Function(int a) p) {}

f((a) {});
f((int a) {});
```

''';

class FunctionExpressionWithIncorrectTypes extends LintRule
implements NodeLintRule {
FunctionExpressionWithIncorrectTypes()
: super(
name: 'function_expression_with_incorrect_types',
description: _desc,
details: _details,
group: Group.style);

@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor = _Visitor(this, context);
registry.addFunctionExpression(this, visitor);
}
}

class _Visitor extends SimpleAstVisitor<void> {
_Visitor(this.rule, this.context);

final LintRule rule;
final LinterContext context;

@override
void visitFunctionExpression(FunctionExpression node) {
var currentType = node.staticType;
if (currentType is! FunctionType) return;

var parameterElement = node
.thisOrAncestorMatching<Expression>(
(e) => e.parent is! ParenthesizedExpression)
?.staticParameterElement;
if (parameterElement == null) return;

var expectedType = parameterElement.type;
if (expectedType is! FunctionType) return;

// too hard to check cross nullability
var currentNullability = context.isEnabled(Feature.non_nullable);
var expectedNullability =
(parameterElement.library ?? parameterElement.declaration.library)
?.featureSet
.isEnabled(Feature.non_nullable);
if (expectedNullability == null ||
currentNullability ^ expectedNullability) {
return;
}

// check type of each parameters
var currentParams = currentType.parameters;
var expectedParams = expectedType.parameters;
for (var i = 0; i < currentParams.length; i++) {
var currentParam = currentParams[i];
// if param is mutated, no lint
if (node.body.isPotentiallyMutatedInScope(currentParam) ||
node.body.isPotentiallyMutatedInClosure(currentParam)) {
continue;
}

// if param is not found on target, no lint
var expectedParam = currentParam.isPositional
? expectedParams[i]
: expectedParams
.where((e) => e.name == currentParam.name)
.firstOrNull;
if (expectedParam == null) {
continue;
}

var typeSystem = context.typeSystem;
var currentType = currentParam.type;
var expectedType = expectedParam.type;
// if type are not consistent, lint!
if (currentParam.isRequiredPositional && currentType != expectedType ||
currentParam.isOptional &&
(currentNullability &&
(typeSystem.isNonNullable(expectedType) &&
expectedType !=
typeSystem.promoteToNonNull(currentType) ||
typeSystem.isNullable(expectedType) &&
expectedType != currentType) ||
!currentNullability && expectedType != currentType)) {
rule.reportLint(node.parameters!.parameters
.firstWhere((e) => e.declaredElement == currentParam));
}
}
}
}
69 changes: 69 additions & 0 deletions test_data/rules/function_expression_with_incorrect_types.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// test w/ `dart test -N function_expression_with_incorrect_types`

f(void Function(int a) p) {}
f1(Function p) {}
f2(dynamic p) {}
f3(void Function([int a]) p) {}
f4(void Function({int a}) p) {}
f5(void Function({bool a, bool b, Uri c}) p) {}
f6(void Function(dynamic a) p) {}
f7(void Function(Object? a) p) {}

class MyMap<K, V> {
void f(void Function(int a) p) {}
void ff(void Function(K a) p) {}
}

Function(int a)? p;

g1(int a) {}
g2(int? a) {}
g3(num a) {}

m() {
f((a) {}); // OK
f((int? a) {}); // LINT
f((num a) {}); // LINT
f(g1); // OK
f(g2); // OK
f(g3); // OK

p = (a) {}; // OK
p = (int? a) {}; // LINT
p = (num a) {}; // LINT
p = g1; // OK
p = g2; // OK
p = g3; // OK

f1((int? a) {}); // OK
f2((int? a) {}); // OK

// mutation of param
f((int? a) { a = null; }); // OK
f((int? a) { () {a = null;}(); }); // OK

// optional params
f3(([int? a]) {}); // OK
f3(([int a = 1]) {}); // OK
f4(({int? a}) {}); // OK
f4(({int a = 1}) {}); // OK
f4(({num? a}) {}); // LINT
f4(({num a = 1}) {}); // LINT

// different name
f((num b) {}); // LINT

// inversed names
f5(({bool b, bool a, Uri c}) {}); // OK

// Object? vs. dynamic
f6((Object? a) {}); // OK
f7((dynamic a) {}); // OK
MyMap().f((int? a) {}); // LINT
MyMap().ff((Object? a) {}); // LINT
MyMap<int, String>().ff((int? a) {}); // LINT
}