diff --git a/pkg/analysis_server/lib/src/services/correction/dart/remove_unused.dart b/pkg/analysis_server/lib/src/services/correction/dart/remove_unused.dart index ba9b690ff53..adc0a5e228e 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/remove_unused.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/remove_unused.dart @@ -116,8 +116,9 @@ class RemoveUnusedField extends _RemoveUnused { sourceRanges.add(sourceRange); } + final uniqueSourceRanges = _uniqueSourceRanges(sourceRanges); await builder.addDartFileEdit(file, (builder) { - for (var sourceRange in sourceRanges) { + for (var sourceRange in uniqueSourceRanges) { builder.addDeletion(sourceRange); } }); @@ -182,6 +183,24 @@ class RemoveUnusedField extends _RemoveUnused { } } + /// Return [SourceRange]s that are not covered by other in [ranges]. + /// If there is any intersection, it must be fully covered, never partially. + List _uniqueSourceRanges(List ranges) { + var result = []; + candidates: + for (var candidate in ranges) { + for (var other in ranges) { + if (identical(candidate, other)) { + continue; + } else if (candidate.coveredBy(other)) { + continue candidates; + } + } + result.add(candidate); + } + return result; + } + /// Return an instance of this class. Used as a tear-off in `FixProcessor`. static RemoveUnusedField newInstance() => RemoveUnusedField(); } diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_field_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_field_test.dart index b0ca4c6dbb1..8524de589b3 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/remove_unused_field_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/remove_unused_field_test.dart @@ -192,6 +192,23 @@ class A { '''); } + Future test_unusedField_notUsed_assign_nested() async { + await resolveTestCode(r''' +class A { + var _f; + main() { + _f = () { _f = 0; }; + } +} +'''); + await assertHasFix(r''' +class A { + main() { + } +} +'''); + } + Future test_unusedField_notUsed_compoundAssign() async { await resolveTestCode(r''' class A {