Fix the extract method refactoring to correctly handle nullable return types

Change-Id: I2a885887a8d871f0c61afd6648843b914c59022d
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/204626
Reviewed-by: Samuel Rawlins <srawlins@google.com>
Commit-Queue: Brian Wilkerson <brianwilkerson@google.com>
This commit is contained in:
Brian Wilkerson 2021-06-23 01:10:07 +00:00 committed by commit-bot@chromium.org
parent 3a4b3514bc
commit 9b4ff5e5a6
3 changed files with 45 additions and 1 deletions

View file

@ -17,6 +17,7 @@ import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/precedence.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/extensions.dart';
@ -865,6 +866,7 @@ class CorrectionUtils {
return _getTypeCodeElementArguments(
librariesToImport: librariesToImport,
element: aliasElement,
isNullable: type.nullabilitySuffix == NullabilitySuffix.question,
typeArguments: aliasArguments,
);
}
@ -895,6 +897,7 @@ class CorrectionUtils {
return _getTypeCodeElementArguments(
librariesToImport: librariesToImport,
element: type.element,
isNullable: type.nullabilitySuffix == NullabilitySuffix.question,
typeArguments: type.typeArguments,
);
}
@ -1161,6 +1164,7 @@ class CorrectionUtils {
String? _getTypeCodeElementArguments({
required Set<Source> librariesToImport,
required Element element,
required bool isNullable,
required List<DartType> typeArguments,
}) {
var sb = StringBuffer();
@ -1188,6 +1192,9 @@ class CorrectionUtils {
// append simple name
var name = element.displayName;
sb.write(name);
if (isNullable) {
sb.write('?');
}
// append type arguments
if (typeArguments.isNotEmpty) {

View file

@ -763,6 +763,43 @@ void res(int a, int b) {
''');
}
Future<void> test_statements_nullableReturnType() {
addTestFile('''
void foo(int b) {
// start
int? x;
if (b < 2) {
x = 42;
}
if (b >= 2) {
x = 43;
}
// end
print(x!);
}
''');
_setOffsetLengthForStartEnd();
return assertSuccessfulRefactoring(_computeChange, '''
void foo(int b) {
// start
int? x = res(b);
// end
print(x!);
}
int? res(int b) {
int? x;
if (b < 2) {
x = 42;
}
if (b >= 2) {
x = 43;
}
return x;
}
''');
}
Future<Response> _computeChange() async {
await _prepareOptions();
// send request with the options

View file

@ -1209,7 +1209,7 @@ f(bool p) {
_createRefactoringForStartEndComments();
// do check
await refactoring.checkInitialConditions();
expect(refactoring.returnType, 'int');
expect(refactoring.returnType, 'int?');
}
Future<void> test_returnType_statements_void() async {