Handle FieldDeclaration in ConvertToFunctionDeclaration
Closes https://github.com/dart-lang/sdk/pull/61816
GitOrigin-RevId: f0d47760802bf55fc032792c6dbc91a2b2b2a5c4
Change-Id: Iea5a95d6f10b3cb18591b22f1d32ef8985e641bc
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/457460
Reviewed-by: Samuel Rawlins <srawlins@google.com>
Commit-Queue: Samuel Rawlins <srawlins@google.com>
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart
index 70a4183..674fb9b 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/convert_to_function_declaration.dart
@@ -4,6 +4,7 @@
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server_plugin/edit/dart/correction_producer.dart';
+import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
@@ -42,7 +43,14 @@
var variables = parent.variables;
var grandParent = parent.parent;
- if (grandParent is! VariableDeclarationStatement) return;
+ Token grandParentSemicolon;
+ if (grandParent is VariableDeclarationStatement) {
+ grandParentSemicolon = grandParent.semicolon;
+ } else if (grandParent is FieldDeclaration) {
+ grandParentSemicolon = grandParent.semicolon;
+ } else {
+ return;
+ }
var previous = _previous(variables, node);
var next = _next(variables, node);
@@ -152,7 +160,7 @@
}
} else if (initializer is FunctionExpression &&
initializer.body is BlockFunctionBody) {
- builder.addDeletion(range.token(grandParent.semicolon));
+ builder.addDeletion(range.token(grandParentSemicolon));
}
});
}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/convert_to_function_declaration_test.dart b/pkg/analysis_server/test/src/services/correction/fix/convert_to_function_declaration_test.dart
index ff8caf2..44aa9b2 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/convert_to_function_declaration_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/convert_to_function_declaration_test.dart
@@ -113,6 +113,27 @@
''');
}
+ Future<void> test_class_field() async {
+ await resolveTestCode('''
+class F {
+ final v1 = () => 42;
+
+ void f() {
+ v1();
+ }
+}
+''');
+ await assertHasFix('''
+class F {
+ int v1() => 42;
+
+ void f() {
+ v1();
+ }
+}
+''');
+ }
+
Future<void> test_declaration_different() async {
await resolveTestCode('''
void f() {