[analysis_server] Dot shorthands: Update AddConst fix to add const to dot shorthand constructor invocations.
The `AddConst` fix is triggered by the `PreferConstConstructors` lint and this CL updates the fix to add `const` to dot shorthand constructor invocations that can be made constant.
Fixes: https://github.com/dart-lang/sdk/issues/61163
Bug: https://github.com/dart-lang/sdk/issues/60994
Change-Id: I4520c1edf807c041f38f5477f48ab1b1327732b5
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/441720
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
Commit-Queue: Kallen Tu <kallentu@google.com>
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart
index 60e8a87..c6724ef 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/add_const.dart
@@ -95,7 +95,12 @@
await _insertBeforeNode(builder, targetNode);
return;
}
- if (targetNode case InstanceCreationExpression(:var parent, :var keyword)) {
+ if (targetNode
+ case InstanceCreationExpression(:var parent, :var keyword) ||
+ DotShorthandConstructorInvocation(
+ :var parent,
+ constKeyword: var keyword,
+ )) {
var constDeclarations =
getCodeStyleOptions(unitResult.file).preferConstDeclarations;
@@ -110,7 +115,7 @@
return;
}
}
- if (keyword == null) {
+ if (keyword == null && targetNode is Expression) {
await _insertBeforeNode(builder, targetNode);
return;
}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_const_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_const_test.dart
index df1f1e3..df75478 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/add_const_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/add_const_test.dart
@@ -626,6 +626,48 @@
@override
String get lintCode => LintNames.prefer_const_constructors;
+ Future<void> test_dotShorthand_named() async {
+ await resolveTestCode('''
+class C {
+ const C.named();
+}
+void f() {
+ C c = .named();
+ print(c);
+}
+''');
+ await assertHasFix('''
+class C {
+ const C.named();
+}
+void f() {
+ C c = const .named();
+ print(c);
+}
+''');
+ }
+
+ Future<void> test_dotShorthand_unnamed() async {
+ await resolveTestCode('''
+class C {
+ const C();
+}
+void f() {
+ C c = .new();
+ print(c);
+}
+''');
+ await assertHasFix('''
+class C {
+ const C();
+}
+void f() {
+ C c = const .new();
+ print(c);
+}
+''');
+ }
+
Future<void> test_final_variable() async {
createAnalysisOptionsFile(
lints: [