Commit 28366002 authored by Alexandre Ardhuin's avatar Alexandre Ardhuin Committed by GitHub

enable lint prefer_foreach (#12674)

* enable lint prefer_foreach

* fix tests
parent 872d83a3
...@@ -119,7 +119,7 @@ linter: ...@@ -119,7 +119,7 @@ linter:
# - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods
- prefer_final_fields - prefer_final_fields
- prefer_final_locals - prefer_final_locals
# - prefer_foreach # not yet tested - prefer_foreach
# - prefer_function_declarations_over_variables # not yet tested # - prefer_function_declarations_over_variables # not yet tested
- prefer_initializing_formals - prefer_initializing_formals
# - prefer_interpolation_to_compose_strings # not yet tested # - prefer_interpolation_to_compose_strings # not yet tested
......
...@@ -113,7 +113,7 @@ linter: ...@@ -113,7 +113,7 @@ linter:
# - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods # - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods
- prefer_final_fields - prefer_final_fields
- prefer_final_locals - prefer_final_locals
# - prefer_foreach # not yet tested - prefer_foreach
# - prefer_function_declarations_over_variables # not yet tested # - prefer_function_declarations_over_variables # not yet tested
- prefer_initializing_formals - prefer_initializing_formals
# - prefer_interpolation_to_compose_strings # not yet tested # - prefer_interpolation_to_compose_strings # not yet tested
......
...@@ -293,8 +293,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten ...@@ -293,8 +293,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
@override @override
void dispose() { void dispose() {
for (int pointer in _pointers.keys.toList()) _pointers.keys.toList().forEach(_removeState);
_removeState(pointer);
assert(_pointers.isEmpty); assert(_pointers.isEmpty);
_pointers = null; _pointers = null;
super.dispose(); super.dispose();
......
...@@ -199,9 +199,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer { ...@@ -199,9 +199,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer {
} }
void _clearTrackers() { void _clearTrackers() {
final List<_TapTracker> localTrackers = new List<_TapTracker>.from(_trackers.values); _trackers.values.toList().forEach(_reject);
for (_TapTracker tracker in localTrackers)
_reject(tracker);
assert(_trackers.isEmpty); assert(_trackers.isEmpty);
} }
......
...@@ -709,8 +709,7 @@ class TextStyle extends Diagnosticable { ...@@ -709,8 +709,7 @@ class TextStyle extends Diagnosticable {
final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)); final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info));
properties.add(new DiagnosticsProperty<bool>('${prefix}inherit', inherit, level: (!styleSpecified && inherit) ? DiagnosticLevel.fine : DiagnosticLevel.info)); properties.add(new DiagnosticsProperty<bool>('${prefix}inherit', inherit, level: (!styleSpecified && inherit) ? DiagnosticLevel.fine : DiagnosticLevel.info));
for (DiagnosticsNode style in styles) styles.forEach(properties.add);
properties.add(style);
if (!styleSpecified) if (!styleSpecified)
properties.add(new FlagProperty('inherit', value: inherit, ifTrue: '$prefix<all styles inherited>', ifFalse: '$prefix<no style specified>')); properties.add(new FlagProperty('inherit', value: inherit, ifTrue: '$prefix<all styles inherited>', ifFalse: '$prefix<no style specified>'));
......
...@@ -2736,9 +2736,7 @@ abstract class ContainerRenderObjectMixin<ChildType extends RenderObject, Parent ...@@ -2736,9 +2736,7 @@ abstract class ContainerRenderObjectMixin<ChildType extends RenderObject, Parent
/// Add all the children to the end of this render object's child list. /// Add all the children to the end of this render object's child list.
void addAll(List<ChildType> children) { void addAll(List<ChildType> children) {
if (children != null) children?.forEach(add);
for (ChildType child in children)
add(child);
} }
void _removeFromChildList(ChildType child) { void _removeFromChildList(ChildType child) {
......
...@@ -438,10 +438,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin { ...@@ -438,10 +438,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin {
@override @override
void redepthChildren() { void redepthChildren() {
if (_children != null) { _children?.forEach(redepthChild);
for (SemanticsNode child in _children)
redepthChild(child);
}
} }
@override @override
......
...@@ -219,8 +219,7 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver ...@@ -219,8 +219,7 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver
@override @override
void removeAll() { void removeAll() {
super.removeAll(); super.removeAll();
for (RenderBox child in _keepAliveBucket.values) _keepAliveBucket.values.forEach(dropChild);
dropChild(child);
_keepAliveBucket.clear(); _keepAliveBucket.clear();
} }
...@@ -274,15 +273,13 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver ...@@ -274,15 +273,13 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver
@override @override
void redepthChildren() { void redepthChildren() {
super.redepthChildren(); super.redepthChildren();
for (RenderBox child in _keepAliveBucket.values) _keepAliveBucket.values.forEach(redepthChild);
redepthChild(child);
} }
@override @override
void visitChildren(RenderObjectVisitor visitor) { void visitChildren(RenderObjectVisitor visitor) {
super.visitChildren(visitor); super.visitChildren(visitor);
for (RenderBox child in _keepAliveBucket.values) _keepAliveBucket.values.forEach(visitor);
visitor(child);
} }
@override @override
......
...@@ -384,10 +384,7 @@ class RenderTable extends RenderBox { ...@@ -384,10 +384,7 @@ class RenderTable extends RenderBox {
_configuration = configuration; _configuration = configuration;
_defaultVerticalAlignment = defaultVerticalAlignment; _defaultVerticalAlignment = defaultVerticalAlignment;
_textBaseline = textBaseline; _textBaseline = textBaseline;
if (children != null) { children?.forEach(addRow);
for (List<RenderBox> row in children)
addRow(row);
}
} }
// Children are stored in row-major order. // Children are stored in row-major order.
...@@ -628,8 +625,7 @@ class RenderTable extends RenderBox { ...@@ -628,8 +625,7 @@ class RenderTable extends RenderBox {
y += 1; y += 1;
} }
// drop all the lost children // drop all the lost children
for (RenderBox oldChild in lostChildren) lostChildren.forEach(dropChild);
dropChild(oldChild);
// update our internal values // update our internal values
_columns = columns; _columns = columns;
_rows = cells.length ~/ columns; _rows = cells.length ~/ columns;
...@@ -652,8 +648,7 @@ class RenderTable extends RenderBox { ...@@ -652,8 +648,7 @@ class RenderTable extends RenderBox {
_children.clear(); _children.clear();
_columns = cells.isNotEmpty ? cells.first.length : 0; _columns = cells.isNotEmpty ? cells.first.length : 0;
_rows = 0; _rows = 0;
for (List<RenderBox> row in cells) cells.forEach(addRow);
addRow(row);
assert(_children.length == rows * columns); assert(_children.length == rows * columns);
} }
......
...@@ -1736,8 +1736,7 @@ class _InactiveElements { ...@@ -1736,8 +1736,7 @@ class _InactiveElements {
final List<Element> elements = _elements.toList()..sort(Element._sort); final List<Element> elements = _elements.toList()..sort(Element._sort);
_elements.clear(); _elements.clear();
try { try {
for (Element element in elements.reversed) elements.reversed.forEach(_unmount);
_unmount(element);
} finally { } finally {
assert(_elements.isEmpty); assert(_elements.isEmpty);
_locked = false; _locked = false;
......
...@@ -791,8 +791,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin { ...@@ -791,8 +791,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
}()); }());
push(_routeNamed(Navigator.defaultRouteName)); push(_routeNamed(Navigator.defaultRouteName));
} else { } else {
for (Route<dynamic> route in plannedInitialRoutes) plannedInitialRoutes.forEach(push);
push(route);
} }
} else { } else {
Route<dynamic> route; Route<dynamic> route;
...@@ -1328,8 +1327,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin { ...@@ -1328,8 +1327,7 @@ class NavigatorState extends State<Navigator> with TickerProviderStateMixin {
absorber?.absorbing = true; absorber?.absorbing = true;
}); });
} }
for (int pointer in _activePointers.toList()) _activePointers.toList().forEach(WidgetsBinding.instance.cancelPointer);
WidgetsBinding.instance.cancelPointer(pointer);
} }
@override @override
......
...@@ -36,8 +36,7 @@ class TestTree extends Object with DiagnosticableTreeMixin { ...@@ -36,8 +36,7 @@ class TestTree extends Object with DiagnosticableTreeMixin {
if (style != null) if (style != null)
properties.defaultDiagnosticsTreeStyle = style; properties.defaultDiagnosticsTreeStyle = style;
for (DiagnosticsNode property in this.properties) this.properties.forEach(properties.add);
properties.add(property);
} }
} }
......
...@@ -28,8 +28,7 @@ void main() { ...@@ -28,8 +28,7 @@ void main() {
scheduler.scheduleTask(() { executedTasks.add(x); }, Priority.idle + x); scheduler.scheduleTask(() { executedTasks.add(x); }, Priority.idle + x);
} }
for (int x in input) input.forEach(scheduleAddingTask);
scheduleAddingTask(x);
strategy.allowedPriority = 100; strategy.allowedPriority = 100;
for (int i = 0; i < 3; i += 1) for (int i = 0; i < 3; i += 1)
......
...@@ -26,13 +26,11 @@ class LinkedScrollController extends ScrollController { ...@@ -26,13 +26,11 @@ class LinkedScrollController extends ScrollController {
void setParent(ScrollController newParent) { void setParent(ScrollController newParent) {
if (_parent != null) { if (_parent != null) {
for (ScrollPosition position in positions) positions.forEach(_parent.detach);
_parent.detach(position);
} }
_parent = newParent; _parent = newParent;
if (_parent != null) { if (_parent != null) {
for (ScrollPosition position in positions) positions.forEach(_parent.attach);
_parent.attach(position);
} }
} }
...@@ -54,8 +52,7 @@ class LinkedScrollController extends ScrollController { ...@@ -54,8 +52,7 @@ class LinkedScrollController extends ScrollController {
@override @override
void dispose() { void dispose() {
if (_parent != null) { if (_parent != null) {
for (ScrollPosition position in positions) positions.forEach(_parent.detach);
_parent.detach(position);
} }
super.dispose(); super.dispose();
} }
......
...@@ -194,9 +194,7 @@ class AssetBundle { ...@@ -194,9 +194,7 @@ class AssetBundle {
void dump() { void dump() {
printTrace('Dumping AssetBundle:'); printTrace('Dumping AssetBundle:');
for (String archivePath in entries.keys.toList()..sort()) { (entries.keys.toList()..sort()).forEach(printTrace);
printTrace(archivePath);
}
} }
} }
......
...@@ -55,8 +55,7 @@ Future<List<int>> _attempt(Uri url) async { ...@@ -55,8 +55,7 @@ Future<List<int>> _attempt(Uri url) async {
printTrace('Received response from server, collecting bytes...'); printTrace('Received response from server, collecting bytes...');
try { try {
final BytesBuilder responseBody = new BytesBuilder(copy: false); final BytesBuilder responseBody = new BytesBuilder(copy: false);
await for (List<int> chunk in response) await response.forEach(responseBody.add);
responseBody.add(chunk);
return responseBody.takeBytes(); return responseBody.takeBytes();
} on IOException catch (error) { } on IOException catch (error) {
printTrace('Download error: $error'); printTrace('Download error: $error');
......
...@@ -142,10 +142,8 @@ class ItemListNotifier<T> { ...@@ -142,10 +142,8 @@ class ItemListNotifier<T> {
_items = updatedSet; _items = updatedSet;
for (T item in addedItems) addedItems.forEach(_addedController.add);
_addedController.add(item); removedItems.forEach(_removedController.add);
for (T item in removedItems)
_removedController.add(item);
} }
/// Close the streams. /// Close the streams.
......
...@@ -131,8 +131,7 @@ class ResidentCompiler { ...@@ -131,8 +131,7 @@ class ResidentCompiler {
final String inputKey = new Uuid().generateV4(); final String inputKey = new Uuid().generateV4();
_server.stdin.writeln('recompile $inputKey'); _server.stdin.writeln('recompile $inputKey');
for (String invalidatedFile in invalidatedFiles) invalidatedFiles.forEach(_server.stdin.writeln);
_server.stdin.writeln(invalidatedFile);
_server.stdin.writeln(inputKey); _server.stdin.writeln(inputKey);
return stdoutHandler.outputFilename.future; return stdoutHandler.outputFilename.future;
......
...@@ -478,8 +478,7 @@ class DevFS { ...@@ -478,8 +478,7 @@ class DevFS {
} }
// No need to send source files because all compilation is done on the // No need to send source files because all compilation is done on the
// host and result of compilation is single kernel file. // host and result of compilation is single kernel file.
for (Uri fileUri in filesUris) filesUris.forEach(dirtyEntries.remove);
dirtyEntries.remove(fileUri);
printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files');
final String compiledBinary = fullRestart final String compiledBinary = fullRestart
? await compile( ? await compile(
......
...@@ -91,7 +91,7 @@ class MockHttpClientRequest implements io.HttpClientRequest { ...@@ -91,7 +91,7 @@ class MockHttpClientRequest implements io.HttpClientRequest {
} }
} }
class MockHttpClientResponse implements io.HttpClientResponse { class MockHttpClientResponse extends Stream<List<int>> implements io.HttpClientResponse {
MockHttpClientResponse(this.statusCode); MockHttpClientResponse(this.statusCode);
@override @override
......
...@@ -45,7 +45,7 @@ void main() { ...@@ -45,7 +45,7 @@ void main() {
final String output = await compile(sdkRoot: '/path/to/sdkroot', final String output = await compile(sdkRoot: '/path/to/sdkroot',
mainPath: '/path/to/main.dart' mainPath: '/path/to/main.dart'
); );
verifyNever(mockFrontendServerStdIn.writeln(any)); expect(mockFrontendServerStdIn.getAndClear(), isEmpty);
expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n')); expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n'));
expect(output, equals('/path/to/main.dart.dill')); expect(output, equals('/path/to/main.dart.dill'));
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
...@@ -64,7 +64,7 @@ void main() { ...@@ -64,7 +64,7 @@ void main() {
final String output = await compile(sdkRoot: '/path/to/sdkroot', final String output = await compile(sdkRoot: '/path/to/sdkroot',
mainPath: '/path/to/main.dart' mainPath: '/path/to/main.dart'
); );
verifyNever(mockFrontendServerStdIn.writeln(any)); expect(mockFrontendServerStdIn.getAndClear(), isEmpty);
expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n')); expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n'));
expect(output, equals(null)); expect(output, equals(null));
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
...@@ -110,7 +110,7 @@ void main() { ...@@ -110,7 +110,7 @@ void main() {
final String output = await generator.recompile( final String output = await generator.recompile(
'/path/to/main.dart', null /* invalidatedFiles */ '/path/to/main.dart', null /* invalidatedFiles */
); );
verify(mockFrontendServerStdIn.writeln('compile /path/to/main.dart')); expect(mockFrontendServerStdIn.getAndClear(), 'compile /path/to/main.dart\n');
verifyNoMoreInteractions(mockFrontendServerStdIn); verifyNoMoreInteractions(mockFrontendServerStdIn);
expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n')); expect(logger.traceText, equals('compile debug message: line1\ncompile debug message: line2\n'));
expect(output, equals('/path/to/main.dart.dill')); expect(output, equals('/path/to/main.dart.dill'));
...@@ -125,12 +125,13 @@ void main() { ...@@ -125,12 +125,13 @@ void main() {
when(mockFrontendServer.stdout).thenReturn(streamController.stream); when(mockFrontendServer.stdout).thenReturn(streamController.stream);
streamController.add(UTF8.encode('result abc\nline0\nline1\nabc /path/to/main.dart.dill\n')); streamController.add(UTF8.encode('result abc\nline0\nline1\nabc /path/to/main.dart.dill\n'));
await generator.recompile('/path/to/main.dart', null /* invalidatedFiles */); await generator.recompile('/path/to/main.dart', null /* invalidatedFiles */);
verify(mockFrontendServerStdIn.writeln('compile /path/to/main.dart')); expect(mockFrontendServerStdIn.getAndClear(), 'compile /path/to/main.dart\n');
await _recompile(streamController, generator, mockFrontendServerStdIn, await _recompile(streamController, generator, mockFrontendServerStdIn,
'result abc\nline1\nline2\nabc /path/to/main.dart.dill\n'); 'result abc\nline1\nline2\nabc /path/to/main.dart.dill\n');
verifyNoMoreInteractions(mockFrontendServerStdIn); verifyNoMoreInteractions(mockFrontendServerStdIn);
expect(mockFrontendServerStdIn.getAndClear(), isEmpty);
expect(logger.traceText, equals( expect(logger.traceText, equals(
'compile debug message: line0\ncompile debug message: line1\n' 'compile debug message: line0\ncompile debug message: line1\n'
'compile debug message: line1\ncompile debug message: line2\n' 'compile debug message: line1\ncompile debug message: line2\n'
...@@ -148,7 +149,7 @@ void main() { ...@@ -148,7 +149,7 @@ void main() {
'result abc\nline0\nline1\nabc /path/to/main.dart.dill\n' 'result abc\nline0\nline1\nabc /path/to/main.dart.dill\n'
)); ));
await generator.recompile('/path/to/main.dart', null /* invalidatedFiles */); await generator.recompile('/path/to/main.dart', null /* invalidatedFiles */);
verify(mockFrontendServerStdIn.writeln('compile /path/to/main.dart')); expect(mockFrontendServerStdIn.getAndClear(), 'compile /path/to/main.dart\n');
await _recompile(streamController, generator, mockFrontendServerStdIn, await _recompile(streamController, generator, mockFrontendServerStdIn,
'result abc\nline1\nline2\nabc /path/to/main.dart.dill\n'); 'result abc\nline1\nline2\nabc /path/to/main.dart.dill\n');
...@@ -156,6 +157,7 @@ void main() { ...@@ -156,6 +157,7 @@ void main() {
'result abc\nline2\nline3\nabc /path/to/main.dart.dill\n'); 'result abc\nline2\nline3\nabc /path/to/main.dart.dill\n');
verifyNoMoreInteractions(mockFrontendServerStdIn); verifyNoMoreInteractions(mockFrontendServerStdIn);
expect(mockFrontendServerStdIn.getAndClear(), isEmpty);
expect(logger.traceText, equals( expect(logger.traceText, equals(
'compile debug message: line0\ncompile debug message: line1\n' 'compile debug message: line0\ncompile debug message: line1\n'
'compile debug message: line1\ncompile debug message: line2\n' 'compile debug message: line1\ncompile debug message: line2\n'
...@@ -177,15 +179,33 @@ Future<Null> _recompile(StreamController<List<int>> streamController, ...@@ -177,15 +179,33 @@ Future<Null> _recompile(StreamController<List<int>> streamController,
}); });
final String output = await generator.recompile(null /* mainPath */, <String>['/path/to/main.dart']); final String output = await generator.recompile(null /* mainPath */, <String>['/path/to/main.dart']);
expect(output, equals('/path/to/main.dart.dill')); expect(output, equals('/path/to/main.dart.dill'));
final String recompileCommand = verify( final String commands = mockFrontendServerStdIn.getAndClear();
mockFrontendServerStdIn.writeln(captureThat(startsWith('recompile '))) final RegExp re = new RegExp(r'^recompile (.*)\n/path/to/main.dart\n(.*)\n$');
).captured[0]; expect(commands, matches(re));
final String token1 = recompileCommand.split(' ')[1]; final Match match = re.firstMatch(commands);
verify(mockFrontendServerStdIn.writeln('/path/to/main.dart')); expect(match[1] == match[2], isTrue);
verify(mockFrontendServerStdIn.writeln(token1)); mockFrontendServerStdIn._stdInWrites.clear();
} }
class MockProcessManager extends Mock implements ProcessManager {} class MockProcessManager extends Mock implements ProcessManager {}
class MockProcess extends Mock implements Process {} class MockProcess extends Mock implements Process {}
class MockStream extends Mock implements Stream<List<int>> {} class MockStream extends Mock implements Stream<List<int>> {}
class MockStdIn extends Mock implements IOSink {} class MockStdIn extends Mock implements IOSink {
final StringBuffer _stdInWrites = new StringBuffer();
String getAndClear() {
final String result = _stdInWrites.toString();
_stdInWrites.clear();
return result;
}
@override
void write([Object o = '']) {
_stdInWrites.write(o);
}
@override
void writeln([Object o = '']) {
_stdInWrites.writeln(o);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment