From ea1bc24fdc6bf23b3a4ea2bc9a4e410a481b41dc Mon Sep 17 00:00:00 2001 From: Robert Nystrom Date: Mon, 23 Feb 2026 18:12:59 -0800 Subject: [PATCH] ConvertToInitializingFormal: Don't discard initializers when deleting the constructor body. ConvertToInitializingFormal can convert an initializer to an initializing formal, or an assignment statement in the body: ```dart class C { int x; C(int x) { this.x = x; } } ``` When converting from an assignment statement, if there are no statements left in the block, it deletes the entire function body. Prior to this CL, it would also erroneously delete any initializers that happened to be on the constructor: ```dart // Before: class C { int? x; int? y; C(int? x) : y = 1 { this.x = x; } } // Result of applying fix: class C { int? x; int? y; C(this.x); // Oops! Where did ": y = 1" go? } ``` Change-Id: I5bd27e925509adc82056b71f4c96432c819bc954 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/482966 Reviewed-by: Samuel Rawlins Commit-Queue: Samuel Rawlins Auto-Submit: Bob Nystrom --- .../dart/convert_to_initializing_formal.dart | 7 ++++++- .../convert_to_initializing_formal_test.dart | 21 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_initializing_formal.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_initializing_formal.dart index 3dd3b253d08..32ea50026a8 100644 --- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_initializing_formal.dart +++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_initializing_formal.dart @@ -181,7 +181,12 @@ class ConvertToInitializingFormal extends ResolvedCorrectionProducer { var functionBody = block.parent; if (statements.length == 1 && functionBody is BlockFunctionBody) { builder.addSimpleReplacement( - range.endEnd(constructor.parameters, functionBody), + range.endEnd( + constructor.initializers.isNotEmpty + ? constructor.initializers.last + : constructor.parameters, + functionBody, + ), ';', ); } else { diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_to_initializing_formal_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_to_initializing_formal_test.dart index 743e9811ee4..18d383054eb 100644 --- a/pkg/analysis_server/test/src/services/correction/fix/convert_to_initializing_formal_test.dart +++ b/pkg/analysis_server/test/src/services/correction/fix/convert_to_initializing_formal_test.dart @@ -144,6 +144,27 @@ class C { '''); } + Future test_assignment_otherInitializer() async { + await resolveTestCode(''' +class C { + int? x; + int? y; + + C({int? x}) : y = 1 { + this.x = x; + } +} +'''); + await assertHasFix(''' +class C { + int? x; + int? y; + + C({this.x}) : y = 1; +} +'''); + } + Future test_assignment_positional_differentType() async { await resolveTestCode(''' class C {