Skip to content

Commit

Permalink
Loosen avoid_function_literals_in_foreach_calls to allow method cha…
Browse files Browse the repository at this point in the history
…ined calls (dart-lang#1593)

* Loosen `avoid_function_literals_in_foreach_calls` to allow chained calls

* Loosen the lint only for method chaining and not for only field/getter chaining

* Add a few more test to cover tear-offs and chaining
  • Loading branch information
dramos07 authored and pq committed Nov 12, 2019
1 parent c366cda commit ba0d059
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
19 changes: 18 additions & 1 deletion lib/src/rules/avoid_function_literals_in_foreach_calls.dart
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,25 @@ class _Visitor extends SimpleAstVisitor<void> {
node.argumentList.arguments.isNotEmpty &&
node.argumentList.arguments[0] is FunctionExpression &&
DartTypeUtilities.implementsInterface(
node.target.staticType, 'Iterable', 'dart.core')) {
node.target.staticType, 'Iterable', 'dart.core') &&
!_hasMethodChaining(node)) {
rule.reportLint(node.function);
}
}
}

bool _hasMethodChaining(MethodInvocation node) {
var exp = node.target;
while (exp is PrefixedIdentifier ||
exp is MethodInvocation ||
exp is PropertyAccess) {
if (exp is PrefixedIdentifier) {
exp = (exp as PrefixedIdentifier).prefix;
} else if (exp is MethodInvocation) {
return true;
} else if (exp is PropertyAccess) {
exp = (exp as PropertyAccess).target;
}
}
return false;
}
34 changes: 31 additions & 3 deletions test/rules/avoid_function_literals_in_foreach_calls.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,45 @@

// test w/ `pub run test -N avoid_function_literals_in_foreach_calls`

class Person {
Iterable<Person> children;
}

void main() {
Iterable<String> people;

for (var person in people) { // OK
print(person);
print('$person!');
}
people.forEach((person) { // LINT
print(person);
print('$person!');
});

people.forEach((person) => print(person)); // LINT
people.forEach((person) => print('$person!')); // LINT

people.forEach(print); // OK

people
.where((person) => person != null)
.map((person) => person.toUpperCase())
.forEach((person) => print('$person!')); // OK

people
.where((person) => person != null)
.map((person) => person.toUpperCase())
.forEach(print); // OK

Person()
.children
.firstWhere((person) => person != null)
.children
.forEach((person) => print('$person!')); // OK

Person().children.forEach(print); // OK

Person()
.children
.first
.children
.forEach((person) => print('$person!')); // LINT
}

0 comments on commit ba0d059

Please sign in to comment.