Legacy. Stop using isNonNullableByDefault in analysis_server/

Change-Id: I10592f99d48877e93fababba2149c39a38f75cc1
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/350460
Commit-Queue: Konstantin Shcheglov <scheglov@google.com>
Reviewed-by: Brian Wilkerson <brianwilkerson@google.com>
This commit is contained in:
Konstantin Shcheglov 2024-02-05 22:46:26 +00:00 committed by Commit Queue
parent 05d7c407cf
commit 4dfb2056c0
19 changed files with 39 additions and 207 deletions

View file

@ -5,7 +5,6 @@
import 'package:analysis_server/protocol/protocol_generated.dart'
show HoverInformation;
import 'package:analysis_server/src/computer/computer_overrides.dart';
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart';
import 'package:analyzer/dart/element/element.dart';
@ -110,7 +109,7 @@ class DartUnitHoverComputer {
/// whether they are const).
String? _elementDisplayString(AstNode node, Element? element) {
var displayString = element?.getDisplayString(
withNullability: _unit.isNonNullableByDefault,
withNullability: true,
multiline: true,
);
@ -253,8 +252,7 @@ class DartUnitHoverComputer {
} else if (node is DartPattern) {
staticType = node.matchedValueType;
}
return staticType?.getDisplayString(
withNullability: _unit.isNonNullableByDefault);
return staticType?.getDisplayString(withNullability: true);
}
static Documentation? computeDocumentation(

View file

@ -5,7 +5,6 @@
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:analysis_server/lsp_protocol/protocol.dart' hide Element;
import 'package:analysis_server/src/lsp/mapping.dart';
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart';
@ -25,13 +24,11 @@ class DartInlayHintComputer {
final path.Context pathContext;
final LineInfo _lineInfo;
final CompilationUnit _unit;
final bool _isNonNullableByDefault;
final List<InlayHint> _hints = [];
DartInlayHintComputer(this.pathContext, ResolvedUnitResult result)
: _unit = result.unit,
_lineInfo = result.lineInfo,
_isNonNullableByDefault = result.unit.isNonNullableByDefault;
_lineInfo = result.lineInfo;
List<InlayHint> compute() {
_unit.accept(_DartInlayHintComputerVisitor(this));
@ -187,14 +184,12 @@ class DartInlayHintComputer {
}
}
// Finally add any nullability suffix.
if (_isNonNullableByDefault) {
switch (type.nullabilitySuffix) {
case NullabilitySuffix.question:
parts.add(InlayHintLabelPart(value: '?'));
case NullabilitySuffix.star:
parts.add(InlayHintLabelPart(value: '*'));
default:
}
switch (type.nullabilitySuffix) {
case NullabilitySuffix.question:
parts.add(InlayHintLabelPart(value: '?'));
case NullabilitySuffix.star:
parts.add(InlayHintLabelPart(value: '*'));
default:
}
}

View file

@ -4,7 +4,6 @@
import 'package:analysis_server/src/collections.dart';
import 'package:analysis_server/src/protocol_server.dart' as proto;
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
@ -50,12 +49,12 @@ class DartUnitOverridesComputer {
var superMember = superElements.isNotEmpty
? proto.newOverriddenMember_fromEngine(
superElements.first.nonSynthetic,
withNullability: _unit.isNonNullableByDefault)
withNullability: true)
: null;
var interfaceMembers = interfaceElements
.map((member) => proto.newOverriddenMember_fromEngine(
member.nonSynthetic,
withNullability: _unit.isNonNullableByDefault))
withNullability: true))
.toList();
_overrides.add(proto.Override(token.offset, token.length,
superclassMember: superMember,

View file

@ -17,7 +17,6 @@ class DartUnitSignatureComputer {
final DartdocDirectiveInfo _dartdocInfo;
final AstNode? _node;
late ArgumentList _argumentList;
final bool _isNonNullableByDefault;
final DocumentationPreference documentationPreference;
DartUnitSignatureComputer(
@ -25,8 +24,7 @@ class DartUnitSignatureComputer {
CompilationUnit unit,
int offset, {
this.documentationPreference = DocumentationPreference.full,
}) : _node = NodeLocator(offset).searchWithin(unit),
_isNonNullableByDefault = unit.isNonNullableByDefault;
}) : _node = NodeLocator(offset).searchWithin(unit);
/// The [ArgumentList] node located by [compute].
ArgumentList get argumentList => _argumentList;
@ -79,7 +77,7 @@ class DartUnitSignatureComputer {
? ParameterKind.REQUIRED_NAMED
: ParameterKind.REQUIRED_POSITIONAL,
param.displayName,
param.type.getDisplayString(withNullability: _isNonNullableByDefault),
param.type.getDisplayString(withNullability: true),
defaultValue: param.defaultValueCode);
}

View file

@ -6,7 +6,6 @@ import 'package:analysis_server/lsp_protocol/protocol.dart' as lsp;
import 'package:analysis_server/src/computer/computer_hover.dart';
import 'package:analysis_server/src/lsp/dartdoc.dart';
import 'package:analysis_server/src/lsp/mapping.dart';
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/dart/ast/element_locator.dart';
@ -21,7 +20,6 @@ class DartTypeArgumentsSignatureComputer {
final AstNode? _node;
final Set<lsp.MarkupKind>? preferredFormats;
late TypeArgumentList _argumentList;
final bool _isNonNullableByDefault;
final DocumentationPreference documentationPreference;
DartTypeArgumentsSignatureComputer(
@ -30,8 +28,7 @@ class DartTypeArgumentsSignatureComputer {
int offset,
this.preferredFormats, {
this.documentationPreference = DocumentationPreference.full,
}) : _node = NodeLocator(offset).searchWithin(unit),
_isNonNullableByDefault = unit.isNonNullableByDefault;
}) : _node = NodeLocator(offset).searchWithin(unit);
/// The [TypeArgumentList] node located by [compute].
TypeArgumentList get argumentList => _argumentList;
@ -58,8 +55,7 @@ class DartTypeArgumentsSignatureComputer {
_argumentList = argumentList;
final label =
element.getDisplayString(withNullability: _isNonNullableByDefault);
final label = element.getDisplayString(withNullability: true);
final documentation = DartUnitHoverComputer.computePreferredDocumentation(
_dartdocInfo, element, documentationPreference);
@ -92,8 +88,7 @@ class DartTypeArgumentsSignatureComputer {
) {
final parameters = typeParameters
.map((param) => lsp.ParameterInformation(
label: param.getDisplayString(
withNullability: _isNonNullableByDefault),
label: param.getDisplayString(withNullability: true),
))
.toList();

View file

@ -4,7 +4,6 @@
import 'package:analysis_server/plugin/analysis/occurrences/occurrences_core.dart';
import 'package:analysis_server/src/protocol_server.dart' as protocol;
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
@ -16,8 +15,8 @@ void addDartOccurrences(OccurrencesCollector collector, CompilationUnit unit) {
unit.accept(visitor);
visitor.elementsOffsets.forEach((engineElement, offsets) {
var length = engineElement.nameLength;
var serverElement = protocol.convertElement(engineElement,
withNullability: unit.isNonNullableByDefault);
var serverElement =
protocol.convertElement(engineElement, withNullability: true);
var occurrences = protocol.Occurrences(serverElement, offsets, length);
collector.addOccurrences(occurrences);
});

View file

@ -40,9 +40,7 @@ class SearchFindElementReferencesHandler extends LegacyHandler {
var result = protocol.SearchFindElementReferencesResult();
if (element != null) {
result.id = searchId;
var withNullability = element.library?.isNonNullableByDefault ?? false;
result.element =
protocol.convertElement(element, withNullability: withNullability);
result.element = protocol.convertElement(element, withNullability: true);
}
sendResult(result);
// search elements

View file

@ -278,9 +278,8 @@ List<Element> _computePath(engine.Element element) {
element = element.enclosingElement.definingCompilationUnit;
}
var withNullability = element.library?.isNonNullableByDefault ?? false;
for (var e in element.withAncestors) {
path.add(convertElement(e, withNullability: withNullability));
path.add(convertElement(e, withNullability: true));
}
return path;
}

View file

@ -24,9 +24,6 @@ class TypeHierarchyComputer {
TypeHierarchyComputer(this._searchEngine, final Element pivotElement)
: helper = TypeHierarchyComputerHelper.fromElement(pivotElement);
bool get _isNonNullableByDefault =>
helper.pivotLibrary.isNonNullableByDefault;
/// Returns the computed type hierarchy, maybe `null`.
Future<List<TypeHierarchyItem>?> compute() async {
var pivotClass = helper.pivotClass;
@ -69,10 +66,9 @@ class TypeHierarchyComputer {
var subMemberElement = helper.findMemberElement(subElement);
var subMemberElementDeclared = subMemberElement?.nonSynthetic;
subItem = TypeHierarchyItem(
convertElement(subElement, withNullability: _isNonNullableByDefault),
convertElement(subElement, withNullability: true),
memberElement: subMemberElementDeclared != null
? convertElement(subMemberElementDeclared,
withNullability: _isNonNullableByDefault)
? convertElement(subMemberElementDeclared, withNullability: true)
: null,
superclass: itemId);
var subItemId = _items.length;
@ -107,20 +103,17 @@ class TypeHierarchyComputer {
String? displayName;
if (typeArguments != null && typeArguments.isNotEmpty) {
var typeArgumentsStr = typeArguments
.map((type) =>
type.getDisplayString(withNullability: _isNonNullableByDefault))
.map((type) => type.getDisplayString(withNullability: true))
.join(', ');
displayName = '${classElement.displayName}<$typeArgumentsStr>';
}
var memberElement = helper.findMemberElement(classElement);
var memberElementDeclared = memberElement?.nonSynthetic;
item = TypeHierarchyItem(
convertElement(classElement,
withNullability: _isNonNullableByDefault),
convertElement(classElement, withNullability: true),
displayName: displayName,
memberElement: memberElementDeclared != null
? convertElement(memberElementDeclared,
withNullability: _isNonNullableByDefault)
? convertElement(memberElementDeclared, withNullability: true)
: null);
_elementItemMap[classElement] = item;
itemId = _items.length;

View file

@ -242,9 +242,6 @@ class SuggestionBuilder {
return _cachedContainingMemberName;
}
bool get _isNonNullableByDefault =>
request.libraryElement.isNonNullableByDefault;
/// Return `true` if the context requires a constant expression.
bool get _preferConstants =>
request.inConstantContext || request.opType.mustBeConst;
@ -812,8 +809,7 @@ class SuggestionBuilder {
required bool appendComma,
int? replacementLength}) {
var name = parameter.name;
var type = parameter.type
.getDisplayString(withNullability: _isNonNullableByDefault);
var type = parameter.type.getDisplayString(withNullability: true);
var completion = name;
if (appendColon) {
@ -873,8 +869,7 @@ class SuggestionBuilder {
elementLocation: parameter.location);
if (parameter is FieldFormalParameterElement) {
_setDocumentation(suggestion, parameter);
suggestion.element =
convertElement(parameter, withNullability: _isNonNullableByDefault);
suggestion.element = convertElement(parameter, withNullability: true);
}
_addSuggestion(suggestion);
@ -890,7 +885,7 @@ class SuggestionBuilder {
int? replacementLength}) {
final name = field.name;
final type = field.type.getDisplayString(
withNullability: _isNonNullableByDefault,
withNullability: true,
);
var completion = name;
@ -978,8 +973,8 @@ class SuggestionBuilder {
displayText: displayText,
elementLocation: element.location,
requiredImports: overrideImports.toList());
suggestion.element = protocol.convertElement(element,
withNullability: _isNonNullableByDefault);
suggestion.element =
protocol.convertElement(element, withNullability: true);
_addSuggestion(
suggestion,
textToMatchOverride: _textToMatchOverride(element),
@ -1045,7 +1040,7 @@ class SuggestionBuilder {
);
final returnType = field.type.getDisplayString(
withNullability: _isNonNullableByDefault,
withNullability: true,
);
_addSuggestion(
@ -1464,7 +1459,7 @@ class SuggestionBuilder {
var suggestedElement = protocol.convertElement(
element,
withNullability: _isNonNullableByDefault,
withNullability: true,
);
var enclosingElement = element.enclosingElement;
@ -1476,7 +1471,7 @@ class SuggestionBuilder {
var returnType = getReturnTypeString(
element,
withNullability: _isNonNullableByDefault,
withNullability: true,
);
List<String>? parameterNames;
@ -1490,7 +1485,7 @@ class SuggestionBuilder {
}).toList();
parameterTypes = element.parameters.map((ParameterElement parameter) {
return parameter.type.getDisplayString(
withNullability: _isNonNullableByDefault,
withNullability: true,
);
}).toList();

View file

@ -465,17 +465,10 @@ class PostfixCompletionProcessor {
return 'Exception';
}
// Only print nullability for non-legacy types in non-legacy libraries.
var showNullability = type.nullabilitySuffix != NullabilitySuffix.star &&
(astNode.root as CompilationUnit)
.declaredElement!
.library
.isNonNullableByDefault;
// Can't catch nullable types, strip `?`s now that we've checked for `*`s.
return type
.withNullability(NullabilitySuffix.none)
.getDisplayString(withNullability: showNullability);
.getDisplayString(withNullability: true);
}
return 'Exception';
}

View file

@ -19,9 +19,6 @@ class AddLate extends ResolvedCorrectionProducer {
@override
Future<void> compute(ChangeBuilder builder) async {
if (!libraryElement.isNonNullableByDefault) {
return;
}
final node = this.node;
if (node is VariableDeclaration) {
var variableList = node.parent;

View file

@ -99,8 +99,7 @@ class AddMissingRequiredArgument extends ResolvedCorrectionProducer {
var codeStyleOptions = getCodeStyleOptions(unitResult.file);
var defaultValue = getDefaultStringParameterValue(
missingParameter, codeStyleOptions,
withNullability: libraryElement.isNonNullableByDefault &&
(missingParameter.library?.isNonNullableByDefault ?? false));
withNullability: true);
await builder.addDartFileEdit(file, (builder) {
builder.addInsertion(offset, (builder) {

View file

@ -104,8 +104,7 @@ class ShadowField extends ResolvedCorrectionProducer {
if (parent is IsExpression && parent.expression == node) {
return enclosingIf(parent);
} else if (parent is BinaryExpression &&
unitResult.libraryElement.isNonNullableByDefault) {
} else if (parent is BinaryExpression) {
var opType = parent.operator.type;
if (opType == TokenType.EQ_EQ || opType == TokenType.BANG_EQ) {
return enclosingIf(parent);

View file

@ -11,7 +11,6 @@ import 'package:analysis_server/src/services/correction/util.dart';
import 'package:analysis_server/src/services/refactoring/legacy/naming_conventions.dart';
import 'package:analysis_server/src/services/refactoring/legacy/refactoring.dart';
import 'package:analysis_server/src/services/refactoring/legacy/refactoring_internal.dart';
import 'package:analysis_server/src/utilities/extensions/ast.dart';
import 'package:analysis_server/src/utilities/strings.dart';
import 'package:analyzer/dart/analysis/code_style_options.dart';
import 'package:analyzer/dart/analysis/features.dart';
@ -86,7 +85,7 @@ class ExtractLocalRefactoringImpl extends RefactoringImpl
if (codeStyleOptions.specifyTypes) {
typeString = singleExpression != null
? singleExpression?.staticType
?.getDisplayString(withNullability: unit.isNonNullableByDefault)
?.getDisplayString(withNullability: true)
: stringLiteralPart != null
? 'String'
: null;

View file

@ -56,11 +56,6 @@ abstract class DartSnippetProducer extends SnippetProducer {
.any(path.contains);
}
/// The nullable suffix to use in this library.
NullabilitySuffix get nullableSuffix => libraryElement.isNonNullableByDefault
? NullabilitySuffix.question
: NullabilitySuffix.none;
/// Adds public imports for any elements fetched by [getClass] and [getMixin]
/// to [builder].
Future<void> addImports(DartFileEditBuilder builder) async {
@ -175,7 +170,7 @@ mixin FlutterWidgetSnippetProducerMixin on FlutterSnippetProducer {
keyName = 'super.key';
} else {
keyName = 'key';
keyType = getType(classKey, nullableSuffix);
keyType = getType(classKey, NullabilitySuffix.question);
keyInitializer = () => builder.write('super(key: key)');
}

View file

@ -185,12 +185,6 @@ extension CompilationUnitExtension on CompilationUnit {
}
return header;
}
/// Return `true` if library being analyzed is non-nullable by default.
///
/// Will return `false` if the AST structure has not been resolved.
bool get isNonNullableByDefault =>
declaredElement?.library.isNonNullableByDefault ?? false;
}
extension DeclaredVariablePatternExtension on DeclaredVariablePattern {

View file

@ -747,100 +747,6 @@ f() {
''');
}
Future<void> test_tryonThrowStatement_nnbd_into_legacy() async {
newFile('$testPackageLibPath/a.dart', r'''
String? x;
''');
await _prepareCompletion('.tryon', '''
// @dart = 2.8
import 'a.dart';
f() {
throw x;.tryon
}
''');
_assertHasChange('Expand .tryon', '''
// @dart = 2.8
import 'a.dart';
f() {
try {
throw x;/*caret*/
} on String catch (e, s) {
print(s);
}
}
''');
}
Future<void> test_tryonThrowStatement_nnbd_into_legacy_nested() async {
newFile('$testPackageLibPath/a.dart', r'''
List<String?> x;
''');
await _prepareCompletion('.tryon', '''
// @dart = 2.8
import 'a.dart';
f() {
throw x;.tryon
}
''');
_assertHasChange('Expand .tryon', '''
// @dart = 2.8
import 'a.dart';
f() {
try {
throw x;/*caret*/
} on List<String> catch (e, s) {
print(s);
}
}
''');
}
Future<void> test_tryonThrowStatement_nnbd_legacy() async {
newFile('$testPackageLibPath/a.dart', r'''
// @dart = 2.8
String x;
''');
await _prepareCompletion('.tryon', '''
import 'a.dart';
f() {
throw x;.tryon
}
''');
_assertHasChange('Expand .tryon', '''
import 'a.dart';
f() {
try {
throw x;/*caret*/
} on String catch (e, s) {
print(s);
}
}
''');
}
Future<void> test_tryonThrowStatement_nnbd_legacy_nested() async {
newFile('$testPackageLibPath/a.dart', r'''
// @dart = 2.8
List<String> x;
''');
await _prepareCompletion('.tryon', '''
import 'a.dart';
f() {
throw x;.tryon
}
''');
_assertHasChange('Expand .tryon', '''
import 'a.dart';
f() {
try {
throw x;/*caret*/
} on List<String> catch (e, s) {
print(s);
}
}
''');
}
Future<void> test_tryonThrowStatement_nnbd_nullable() async {
await _prepareCompletion('.tryon', '''
f() {

View file

@ -11,29 +11,10 @@ import 'fix_processor.dart';
void main() {
defineReflectiveSuite(() {
defineReflectiveTests(AddLatePreNnbdTest);
defineReflectiveTests(AddLateTest);
});
}
@reflectiveTest
class AddLatePreNnbdTest extends FixProcessorTest {
@override
FixKind get kind => DartFixKind.ADD_LATE;
@override
String get testPackageLanguageVersion => '2.9';
Future<void> test_withFinal() async {
await resolveTestCode('''
class C {
final String s;
}
''');
await assertNoFix();
}
}
@reflectiveTest
class AddLateTest extends FixProcessorTest {
@override