Version 2.13.0-178.0.dev
Merge commit 'ed7dd1eda64fdd48c79bf8ad28e0cce400d82a48' into 'dev'
diff --git a/.dart_tool/package_config.json b/.dart_tool/package_config.json
index 8a5f7e9..056b654 100644
--- a/.dart_tool/package_config.json
+++ b/.dart_tool/package_config.json
@@ -11,7 +11,7 @@
"constraint, update this by running tools/generate_package_config.dart."
],
"configVersion": 2,
- "generated": "2021-03-24T13:42:28.071470",
+ "generated": "2021-03-29T21:48:35.411283",
"generator": "tools/generate_package_config.dart",
"packages": [
{
@@ -94,7 +94,7 @@
"name": "analyzer_plugin",
"rootUri": "../pkg/analyzer_plugin",
"packageUri": "lib/",
- "languageVersion": "2.9"
+ "languageVersion": "2.12"
},
{
"name": "analyzer_utilities",
@@ -734,12 +734,6 @@
"languageVersion": "2.12"
},
{
- "name": "uuid",
- "rootUri": "../third_party/pkg/uuid",
- "packageUri": "lib/",
- "languageVersion": "2.0"
- },
- {
"name": "vector_math",
"rootUri": "../third_party/pkg/vector_math",
"packageUri": "lib/",
diff --git a/DEPS b/DEPS
index 4ecf65b..8c93fae 100644
--- a/DEPS
+++ b/DEPS
@@ -102,7 +102,7 @@
"chromedriver_tag": "83.0.4103.39",
"browser_launcher_rev": "12ab9f351a44ac803de9bc17bb2180bb312a9dd7",
- "dartdoc_rev" : "174021f3d76c2a8500b54977c80f32c5bbc099f1",
+ "dartdoc_rev" : "e2d010ed74059be942a78ced5f35f1b8d667ed16",
"ffi_rev": "f3346299c55669cc0db48afae85b8110088bf8da",
"fixnum_rev": "16d3890c6dc82ca629659da1934e412292508bba",
"file_rev": "0e09370f581ab6388d46fda4cdab66638c0171a1",
diff --git a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
index ccb5df1..40d94a7 100644
--- a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
+++ b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
@@ -565,7 +565,7 @@
}
var files = params.files;
for (var file in files.keys) {
- Object overlay = files[file];
+ var overlay = files[file];
if (overlay is RemoveContentOverlay) {
_overlayState.remove(file);
} else if (overlay is AddContentOverlay) {
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/analysis_options/fix_generator.dart b/pkg/analysis_server/lib/src/services/correction/fix/analysis_options/fix_generator.dart
index c435c38..241673e 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/analysis_options/fix_generator.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/analysis_options/fix_generator.dart
@@ -8,6 +8,7 @@
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/utilities/strings.dart';
import 'package:analysis_server/src/utilities/yaml_node_locator.dart';
+import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/source/line_info.dart';
import 'package:analyzer/src/analysis_options/error/option_codes.dart';
@@ -15,6 +16,7 @@
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/lint/options_rule_validator.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
import 'package:yaml/yaml.dart';
@@ -169,7 +171,9 @@
var nodeToDelete = coveringNodePath[index - 1];
deletionRange ??=
_lines(nodeToDelete.span.start.offset, nodeToDelete.span.end.offset);
- var builder = ChangeBuilder();
+ var builder = ChangeBuilder(
+ workspace: _NonDartChangeWorkspace(),
+ );
await builder.addGenericFileEdit(file, (builder) {
builder.addDeletion(deletionRange);
});
@@ -192,3 +196,15 @@
return SourceRange(startOffset, endOffset - startOffset);
}
}
+
+class _NonDartChangeWorkspace implements ChangeWorkspace {
+ @override
+ bool containsFile(String path) {
+ return true;
+ }
+
+ @override
+ AnalysisSession getSession(String path) {
+ throw UnimplementedError('Attempt to work a Dart file.');
+ }
+}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/accessor.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/accessor.dart
index 0d17244..765e120 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/accessor.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/accessor.dart
@@ -49,6 +49,9 @@
return const InvalidResult();
}
+ @override
+ String toString() => 'arguments[$parameter]';
+
/// Return the argument list associated with the [node].
ArgumentList _getArgumentList(AstNode node) {
if (node is Annotation) {
@@ -106,6 +109,9 @@
return const InvalidResult();
}
+ @override
+ String toString() => 'typeArguments[$index]';
+
/// Return the type argument list associated with the [node].
TypeArgumentList _getTypeArgumentList(AstNode node) {
if (node is ExtensionOverride) {
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/expression.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/expression.dart
index 96651b9..9f56ae1 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/expression.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/expression.dart
@@ -41,6 +41,9 @@
}
return null;
}
+
+ @override
+ String toString() => '$leftOperand ${operator.displayName} $rightOperand';
}
/// An expression.
@@ -61,6 +64,9 @@
String evaluateIn(TemplateContext context) {
return value;
}
+
+ @override
+ String toString() => '"$value"';
}
/// An operator used in a binary expression.
@@ -83,4 +89,21 @@
String evaluateIn(TemplateContext context) {
return generator.evaluateIn(context);
}
+
+ @override
+ String toString() => '{$generator}';
+}
+
+extension on Operator {
+ String get displayName {
+ switch (this) {
+ case Operator.and:
+ return '&&';
+ case Operator.equal:
+ return '==';
+ case Operator.notEqual:
+ return '!=';
+ }
+ return 'impossible';
+ }
}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart
index c472d13..04c7d6e 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/modify_parameters.dart
@@ -92,6 +92,7 @@
}
}
argumentsToInsert.sort();
+ argumentsToDelete.sort();
/// Write to the [builder] the argument associated with a single
/// [parameter].
@@ -202,8 +203,20 @@
// The remaining deletion ranges are now ready to be removed.
//
for (var subRange in deletionRanges) {
- builder.addDeletion(range.argumentRange(
- argumentList, subRange.lower, subRange.upper, true));
+ var lower = subRange.lower;
+ var upper = subRange.upper;
+ if (lower == 0 &&
+ upper == arguments.length - 1 &&
+ insertionRanges.isNotEmpty) {
+ // We're removing all of the existing arguments but we've already
+ // inserted new arguments between the parentheses. We need to handle
+ // this case specially because the default code would cause a
+ // `ConflictingEditException`.
+ builder.addDeletion(range.startEnd(arguments[lower], arguments[upper]));
+ } else {
+ builder
+ .addDeletion(range.argumentRange(argumentList, lower, upper, true));
+ }
}
}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/parameter_reference.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/parameter_reference.dart
index e67f425..d2fc364 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/parameter_reference.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/parameter_reference.dart
@@ -22,6 +22,9 @@
}
return null;
}
+
+ @override
+ String toString() => name;
}
/// A reference to a formal parameter.
@@ -54,4 +57,7 @@
}
return argument;
}
+
+ @override
+ String toString() => '$index';
}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/value_generator.dart b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/value_generator.dart
index 527669f..16c8388 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix/data_driven/value_generator.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix/data_driven/value_generator.dart
@@ -40,6 +40,9 @@
}
@override
+ String toString() => accessors.join('.');
+
+ @override
bool validate(TemplateContext context) {
Object target = context.node;
for (var accessor in accessors) {
diff --git a/pkg/analysis_server/test/analysis/update_content_test.dart b/pkg/analysis_server/test/analysis/update_content_test.dart
index d8ee8ac..b817956 100644
--- a/pkg/analysis_server/test/analysis/update_content_test.dart
+++ b/pkg/analysis_server/test/analysis/update_content_test.dart
@@ -233,7 +233,7 @@
expect(params, isNotNull);
var files = params.files;
expect(files, hasLength(1));
- Object overlay = files[filePath];
+ var overlay = files[filePath];
expect(overlay, const TypeMatcher<AddContentOverlay>());
AddContentOverlay addOverlay = overlay;
expect(addOverlay.content, fileContent);
diff --git a/pkg/analysis_server/test/src/services/correction/fix/data_driven/modify_parameters_test.dart b/pkg/analysis_server/test/src/services/correction/fix/data_driven/modify_parameters_test.dart
index 77e7e1f..5791e25 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/data_driven/modify_parameters_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/data_driven/modify_parameters_test.dart
@@ -384,12 +384,44 @@
''');
}
+ Future<void> test_mixed_overlap_addBetweenRemoved_deprecated() async {
+ setPackageContent('''
+class C {
+ @deprecated
+ void m1({int a, int b, int d, int e}) {}
+ void m2({int a, int c, int e}) {}
+}
+''');
+ setPackageData(_modify([
+ 'm1',
+ 'C'
+ ], [
+ AddParameter(1, 'c', true, false, codeTemplate('3')),
+ RemoveParameter(NamedParameterReference('b')),
+ RemoveParameter(NamedParameterReference('d')),
+ ], newName: 'm2'));
+ await resolveTestCode('''
+import '$importUri';
+
+void f(C c) {
+ c.m1(a: 1, b: 2, d: 4, e: 5);
+}
+''');
+ await assertHasFix('''
+import '$importUri';
+
+void f(C c) {
+ c.m2(a: 1, c: 3, e: 5);
+}
+''');
+ }
+
Future<void> test_mixed_overlap_first_deprecated() async {
setPackageContent('''
class C {
@deprecated
- void m1(int a, int b, int d) {}
- void m2( int c, int d) {}
+ void m1(int a, int b, int d) {}
+ void m2( int c, int d) {}
}
''');
setPackageData(_modify([
@@ -420,8 +452,8 @@
setPackageContent('''
class C {
@deprecated
- void m1(int a, int b, int c) {}
- void m2(int a, int d) {}
+ void m1(int a, int b, int c ) {}
+ void m2(int a, int d) {}
}
''');
setPackageData(_modify([
@@ -452,8 +484,8 @@
setPackageContent('''
class C {
@deprecated
- void m1( int b, int c, int e, int f, int g) {}
- void m2(int a, int b, int d, int e, int g) {}
+ void m1( int b, int c, int e, int f, int g) {}
+ void m2(int a, int b, int d, int e, int g) {}
}
''');
setPackageData(_modify([
@@ -481,7 +513,7 @@
''');
}
- Future<void> test_mixed_replaced_deprecated() async {
+ Future<void> test_mixed_replaceAll_deprecated() async {
setPackageContent('''
class C {
@deprecated
@@ -512,6 +544,41 @@
''');
}
+ Future<void> test_mixed_replaceAll_trailingComma_deprecated() async {
+ setPackageContent('''
+class C {
+ @deprecated
+ void m1({int a }) {}
+ void m2({ int b}) {}
+}
+''');
+ setPackageData(_modify([
+ 'm1',
+ 'C'
+ ], [
+ AddParameter(0, 'b', true, false, codeTemplate('0')),
+ RemoveParameter(NamedParameterReference('a')),
+ ], newName: 'm2'));
+ await resolveTestCode('''
+import '$importUri';
+
+void f(C c) {
+ c.m1(
+ a: 1,
+ );
+}
+''');
+ await assertHasFix('''
+import '$importUri';
+
+void f(C c) {
+ c.m2(
+ b: 0,
+ );
+}
+''');
+ }
+
Future<void> test_remove_first_optionalNamed_deprecated() async {
setPackageContent('''
class C {
diff --git a/pkg/analyzer/lib/src/generated/ffi_verifier.dart b/pkg/analyzer/lib/src/generated/ffi_verifier.dart
index f22e8c1..694d0ad 100644
--- a/pkg/analyzer/lib/src/generated/ffi_verifier.dart
+++ b/pkg/analyzer/lib/src/generated/ffi_verifier.dart
@@ -269,13 +269,13 @@
return false;
}
if (!_isValidFfiNativeType(nativeType.returnType,
- allowVoid: true, allowEmptyStruct: false)) {
+ allowVoid: true, allowEmptyStruct: false, allowHandle: true)) {
return false;
}
for (final DartType typeArg in nativeType.normalParameterTypes) {
if (!_isValidFfiNativeType(typeArg,
- allowVoid: false, allowEmptyStruct: false)) {
+ allowVoid: false, allowEmptyStruct: false, allowHandle: true)) {
return false;
}
}
@@ -288,13 +288,21 @@
bool _isValidFfiNativeType(DartType? nativeType,
{bool allowVoid = false,
bool allowEmptyStruct = false,
- bool allowArray = false}) {
+ bool allowArray = false,
+ bool allowHandle = false}) {
if (nativeType is InterfaceType) {
- // Is it a primitive integer/double type (or ffi.Void if we allow it).
final primitiveType = _primitiveNativeType(nativeType);
- if (primitiveType != _PrimitiveDartType.none &&
- (primitiveType != _PrimitiveDartType.void_ || allowVoid)) {
- return true;
+ switch (primitiveType) {
+ case _PrimitiveDartType.void_:
+ return allowVoid;
+ case _PrimitiveDartType.handle:
+ return allowHandle;
+ case _PrimitiveDartType.double:
+ case _PrimitiveDartType.int:
+ return true;
+ case _PrimitiveDartType.none:
+ // These are the cases below.
+ break;
}
if (nativeType.isNativeFunction) {
return _isValidFfiNativeFunctionType(nativeType.typeArguments.single);
@@ -302,7 +310,7 @@
if (nativeType.isPointer) {
final nativeArgumentType = nativeType.typeArguments.single;
return _isValidFfiNativeType(nativeArgumentType,
- allowVoid: true, allowEmptyStruct: true) ||
+ allowVoid: true, allowEmptyStruct: true, allowHandle: true) ||
nativeArgumentType.isStructSubtype ||
nativeArgumentType.isNativeType;
}
@@ -776,12 +784,8 @@
/// associate it with the [errorNode].
void _validateSizeOfAnnotation(AstNode errorNode,
NodeList<Annotation> annotations, int arrayDimensions) {
- final ffiSizeAnnotations = annotations.where((annotation) {
- final element = annotation.element;
- return element is ConstructorElement &&
- element.ffiClass != null &&
- element.enclosingElement.name == 'Array';
- }).toList();
+ final ffiSizeAnnotations =
+ annotations.where((annotation) => annotation.isArray).toList();
if (ffiSizeAnnotations.isEmpty) {
_errorReporter.reportErrorForNode(
@@ -799,17 +803,8 @@
// Check number of dimensions.
final annotation = ffiSizeAnnotations.first;
- final expressions = annotation.arguments!.arguments;
- int annotationDimensions = 0;
- for (var expression in expressions) {
- if (expression is IntegerLiteral) {
- // Element of `@Array(1, 2, 3)`.
- annotationDimensions++;
- } else if (expression is ListLiteral) {
- // Element of `@Array.multi([1, 2, 3])`.
- annotationDimensions += expression.elements.length;
- }
- }
+ final dimensions = annotation.elementAnnotation?.arraySizeDimensions ?? [];
+ final annotationDimensions = dimensions.length;
if (annotationDimensions != arrayDimensions) {
_errorReporter.reportErrorForNode(
FfiCode.SIZE_ANNOTATION_DIMENSIONS, annotation);
@@ -837,6 +832,13 @@
}
extension on Annotation {
+ bool get isArray {
+ final element = this.element;
+ return element is ConstructorElement &&
+ element.ffiClass != null &&
+ element.enclosingElement.name == 'Array';
+ }
+
bool get isPacked {
final element = this.element;
return element is ConstructorElement &&
@@ -846,6 +848,15 @@
}
extension on ElementAnnotation {
+ bool get isArray {
+ final element = this.element;
+ return element is ConstructorElement &&
+ element.ffiClass != null &&
+ element.enclosingElement.name == 'Array';
+ // Note: this is 'Array' instead of '_ArraySize' because it finds the
+ // forwarding factory instead of the forwarded constructor.
+ }
+
bool get isPacked {
final element = this.element;
return element is ConstructorElement &&
@@ -853,6 +864,41 @@
element.enclosingElement.name == 'Packed';
}
+ List<int> get arraySizeDimensions {
+ assert(isArray);
+ final value = computeConstantValue();
+
+ // Element of `@Array.multi([1, 2, 3])`.
+ final listField = value?.getField('dimensions');
+ if (listField != null) {
+ final listValues = listField
+ .toListValue()
+ ?.map((dartValue) => dartValue.toIntValue())
+ .whereType<int>()
+ .toList();
+ if (listValues != null) {
+ return listValues;
+ }
+ }
+
+ // Element of `@Array(1, 2, 3)`.
+ const dimensionFieldNames = [
+ 'dimension1',
+ 'dimension2',
+ 'dimension3',
+ 'dimension4',
+ 'dimension5',
+ ];
+ var result = <int>[];
+ for (final dimensionFieldName in dimensionFieldNames) {
+ final dimensionValue = value?.getField(dimensionFieldName)?.toIntValue();
+ if (dimensionValue != null) {
+ result.add(dimensionValue);
+ }
+ }
+ return result;
+ }
+
int? get packedMemberAlignment {
assert(isPacked);
final value = computeConstantValue();
diff --git a/pkg/analyzer/lib/src/test_utilities/mock_sdk.dart b/pkg/analyzer/lib/src/test_utilities/mock_sdk.dart
index a0ea939..a9f8b0f 100644
--- a/pkg/analyzer/lib/src/test_utilities/mock_sdk.dart
+++ b/pkg/analyzer/lib/src/test_utilities/mock_sdk.dart
@@ -697,10 +697,34 @@
}
class Array<T extends NativeType> extends NativeType {
- external const factory Array(int dimension1,
- [int dimension2, int dimension3, int dimension4, int dimension5]);
+ const factory Array(int dimension1,
+ [int dimension2,
+ int dimension3,
+ int dimension4,
+ int dimension5]) = _ArraySize<T>;
- external const factory Array.multi(List<int> dimensions);
+ const factory Array.multi(List<int> dimensions) = _ArraySize<T>.multi;
+}
+
+class _ArraySize<T extends NativeType> implements Array<T> {
+ final int? dimension1;
+ final int? dimension2;
+ final int? dimension3;
+ final int? dimension4;
+ final int? dimension5;
+
+ final List<int>? dimensions;
+
+ const _ArraySize(this.dimension1,
+ [this.dimension2, this.dimension3, this.dimension4, this.dimension5])
+ : dimensions = null;
+
+ const _ArraySize.multi(this.dimensions)
+ : dimension1 = null,
+ dimension2 = null,
+ dimension3 = null,
+ dimension4 = null,
+ dimension5 = null;
}
extension StructPointer<T extends Struct> on Pointer<T> {
diff --git a/pkg/analyzer/test/src/diagnostics/extra_size_annotation_carray_test.dart b/pkg/analyzer/test/src/diagnostics/extra_size_annotation_carray_test.dart
index b3058ba..e0fd420 100644
--- a/pkg/analyzer/test/src/diagnostics/extra_size_annotation_carray_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/extra_size_annotation_carray_test.dart
@@ -15,6 +15,19 @@
@reflectiveTest
class ExtraSizeAnnotationArray extends PubPackageResolutionTest {
+ test_const() async {
+ await assertNoErrorsInCode(r'''
+import 'dart:ffi';
+
+const EIGHT = 8;
+
+class Struct8BytesInlineArrayInt extends Struct {
+ @Array(EIGHT)
+ Array<Uint8> a0;
+}
+''');
+ }
+
test_one() async {
await assertNoErrorsInCode(r'''
import 'dart:ffi';
diff --git a/pkg/analyzer_plugin/CHANGELOG.md b/pkg/analyzer_plugin/CHANGELOG.md
index 8215421..62081ae 100644
--- a/pkg/analyzer_plugin/CHANGELOG.md
+++ b/pkg/analyzer_plugin/CHANGELOG.md
@@ -1,7 +1,11 @@
## 0.5.0-dev
-- Changed the support version range of the analyzer to `>=0.42.0 <0.43.0`.
+- Changed the support version range of the analyzer to `^1.3.0`.
- Removed `Plugin.fileContentOverlay`, instead `Plugin.resourceProvider` is
now `OverlayResourceProvider`, and `analysis.updateContent` updates it.
+- Removed deprecated `DartChangeBuilder` and `DartChangeBuilderImpl`.
+- Removed deprecated `ChangeBuilder.addFileEdit()`.
+- Stable null safety release.
+- Updated dependencies to null safe releases.
## 0.4.0
- Deprecated the class `DartChangeBuilder` and enhanced `ChangeBuilder` to be
diff --git a/pkg/analyzer_plugin/lib/channel/channel.dart b/pkg/analyzer_plugin/lib/channel/channel.dart
index d2479e0..36ae448 100644
--- a/pkg/analyzer_plugin/lib/channel/channel.dart
+++ b/pkg/analyzer_plugin/lib/channel/channel.dart
@@ -19,7 +19,7 @@
/// client, invoke the [onDone] function. Only one listener is allowed per
/// channel.
void listen(void Function(Request request) onRequest,
- {Function onError, void Function() onDone});
+ {Function? onError, void Function()? onDone});
/// Send the given [notification] to the server.
void sendNotification(Notification notification);
@@ -49,7 +49,7 @@
/// listener is allowed per channel.
void listen(void Function(Response response) onResponse,
void Function(Notification notification) onNotification,
- {void Function(dynamic error) onError, void Function() onDone});
+ {void Function(dynamic error)? onError, void Function()? onDone});
/// Send the given [request] to the plugin.
void sendRequest(Request request);
diff --git a/pkg/analyzer_plugin/lib/plugin/completion_mixin.dart b/pkg/analyzer_plugin/lib/plugin/completion_mixin.dart
index 4bbf59a..f208d20 100644
--- a/pkg/analyzer_plugin/lib/plugin/completion_mixin.dart
+++ b/pkg/analyzer_plugin/lib/plugin/completion_mixin.dart
@@ -34,7 +34,7 @@
var generator = CompletionGenerator(getCompletionContributors(path));
var result = await generator.generateCompletionResponse(request);
result.sendNotifications(channel);
- return result.result;
+ return result.result!;
}
}
diff --git a/pkg/analyzer_plugin/lib/plugin/navigation_mixin.dart b/pkg/analyzer_plugin/lib/plugin/navigation_mixin.dart
index 07dbddb..de11deb 100644
--- a/pkg/analyzer_plugin/lib/plugin/navigation_mixin.dart
+++ b/pkg/analyzer_plugin/lib/plugin/navigation_mixin.dart
@@ -27,7 +27,7 @@
var length = parameters.length;
if (offset < 0 && length < 0) {
offset = 0;
- length = result.content.length;
+ length = result.content?.length ?? 0;
}
return DartNavigationRequestImpl(resourceProvider, offset, length, result);
}
diff --git a/pkg/analyzer_plugin/lib/plugin/plugin.dart b/pkg/analyzer_plugin/lib/plugin/plugin.dart
index 9fb108f..0a5fa70 100644
--- a/pkg/analyzer_plugin/lib/plugin/plugin.dart
+++ b/pkg/analyzer_plugin/lib/plugin/plugin.dart
@@ -33,7 +33,7 @@
/// The communication channel being used to communicate with the analysis
/// server.
- PluginCommunicationChannel _channel;
+ late PluginCommunicationChannel _channel;
/// The resource provider used to access the file system.
final OverlayResourceProvider resourceProvider;
@@ -45,7 +45,7 @@
final SubscriptionManager subscriptionManager = SubscriptionManager();
/// The scheduler used by any analysis drivers that are created.
- AnalysisDriverScheduler analysisDriverScheduler;
+ late AnalysisDriverScheduler analysisDriverScheduler;
/// A table mapping the current context roots to the analysis driver created
/// for that root.
@@ -58,15 +58,15 @@
/// The byte store used by any analysis drivers that are created, or `null` if
/// the cache location isn't known because the 'plugin.version' request has not
/// yet been received.
- ByteStore _byteStore;
+ late ByteStore _byteStore;
/// The SDK manager used to manage SDKs.
- DartSdkManager _sdkManager;
+ late DartSdkManager _sdkManager;
/// Initialize a newly created analysis server plugin. If a resource [provider]
/// is given, then it will be used to access the file system. Otherwise a
/// resource provider that accesses the physical file system will be used.
- ServerPlugin(ResourceProvider provider)
+ ServerPlugin(ResourceProvider? provider)
: resourceProvider = OverlayResourceProvider(
provider ?? PhysicalResourceProvider.INSTANCE) {
analysisDriverScheduler = AnalysisDriverScheduler(performanceLog);
@@ -84,7 +84,7 @@
/// Return the user visible information about how to contact the plugin authors
/// with any problems that are found, or `null` if there is no contact info.
- String get contactInfo => null;
+ String? get contactInfo => null;
/// Return a list of glob patterns selecting the files that this plugin is
/// interested in analyzing.
@@ -106,7 +106,7 @@
}
/// Return the context root containing the file at the given [filePath].
- ContextRoot contextRootContaining(String filePath) {
+ ContextRoot? contextRootContaining(String filePath) {
var pathContext = resourceProvider.pathContext;
/// Return `true` if the given [child] is either the same as or within the
@@ -142,7 +142,7 @@
AnalysisDriverGeneric createAnalysisDriver(ContextRoot contextRoot);
/// Return the driver being used to analyze the file with the given [path].
- AnalysisDriverGeneric driverForPath(String path) {
+ AnalysisDriverGeneric? driverForPath(String path) {
var contextRoot = contextRootContaining(path);
if (contextRoot == null) {
return null;
@@ -161,7 +161,7 @@
throw RequestFailure(
RequestErrorFactory.pluginError('Failed to analyze $path', null));
}
- var result = await (driver as AnalysisDriver).getResult(path);
+ var result = await driver.getResult(path);
var state = result.state;
if (state != ResultState.VALID) {
// Return an error from the request.
@@ -228,7 +228,7 @@
var driver = driverMap.remove(contextRoot);
// The `dispose` method has the side-effect of removing the driver from
// the analysis driver scheduler.
- driver.dispose();
+ driver?.dispose();
}
return AnalysisSetContextRootsResult();
}
@@ -244,7 +244,7 @@
var contextRoot = contextRootContaining(file);
if (contextRoot != null) {
// TODO(brianwilkerson) Which driver should we use if there is no context root?
- var driver = driverMap[contextRoot];
+ var driver = driverMap[contextRoot]!;
filesByDriver.putIfAbsent(driver, () => <String>[]).add(file);
}
}
@@ -274,10 +274,10 @@
/// Throw a [RequestFailure] if the request could not be handled.
Future<AnalysisUpdateContentResult> handleAnalysisUpdateContent(
AnalysisUpdateContentParams parameters) async {
- Map<String, Object> files = parameters.files;
- files.forEach((String filePath, Object overlay) {
+ var files = parameters.files;
+ files.forEach((String filePath, Object? overlay) {
// Prepare the old overlay contents.
- String oldContents;
+ String? oldContents;
try {
if (resourceProvider.hasOverlay(filePath)) {
var file = resourceProvider.getFile(filePath);
@@ -286,7 +286,7 @@
} catch (_) {}
// Prepare the new contents.
- String newContents;
+ String? newContents;
if (overlay is AddContentOverlay) {
newContents = overlay.content;
} else if (overlay is ChangeContentOverlay) {
@@ -359,7 +359,7 @@
/// Handle an 'edit.getRefactoring' request.
///
/// Throw a [RequestFailure] if the request could not be handled.
- Future<EditGetRefactoringResult> handleEditGetRefactoring(
+ Future<EditGetRefactoringResult?> handleEditGetRefactoring(
EditGetRefactoringParams parameters) async {
return null;
}
@@ -367,7 +367,7 @@
/// Handle a 'kythe.getKytheEntries' request.
///
/// Throw a [RequestFailure] if the request could not be handled.
- Future<KytheGetKytheEntriesResult> handleKytheGetKytheEntries(
+ Future<KytheGetKytheEntriesResult?> handleKytheGetKytheEntries(
KytheGetKytheEntriesParams parameters) async {
return null;
}
@@ -503,8 +503,8 @@
/// Compute the response that should be returned for the given [request], or
/// `null` if the response has already been sent.
- Future<Response> _getResponse(Request request, int requestTime) async {
- ResponseResult result;
+ Future<Response?> _getResponse(Request request, int requestTime) async {
+ ResponseResult? result;
switch (request.method) {
case ANALYSIS_REQUEST_GET_NAVIGATION:
var params = AnalysisGetNavigationParams.fromRequest(request);
@@ -577,7 +577,7 @@
Future<void> _onRequest(Request request) async {
var requestTime = DateTime.now().millisecondsSinceEpoch;
var id = request.id;
- Response response;
+ Response? response;
try {
response = await _getResponse(request, requestTime);
} on RequestFailure catch (exception) {
diff --git a/pkg/analyzer_plugin/lib/protocol/protocol.dart b/pkg/analyzer_plugin/lib/protocol/protocol.dart
index e661567..25684ff 100644
--- a/pkg/analyzer_plugin/lib/protocol/protocol.dart
+++ b/pkg/analyzer_plugin/lib/protocol/protocol.dart
@@ -30,7 +30,7 @@
/// A table mapping the names of notification parameters to their values, or
/// `null` if there are no notification parameters.
- final Map<String, Object> params;
+ final Map<String, Object>? params;
/// Initialize a newly created [Notification] to have the given [event] name.
/// If [params] is provided, it will be used as the params; otherwise no
@@ -48,6 +48,7 @@
Map<String, Object> toJson() {
var jsonObject = <String, Object>{};
jsonObject[EVENT] = event;
+ var params = this.params;
if (params != null) {
jsonObject[PARAMS] = params;
}
@@ -83,13 +84,13 @@
/// The time (milliseconds since epoch) at which the server made the request,
/// or `null` if this information is not provided by the server.
- final int serverRequestTime;
+ final int? serverRequestTime;
/// Initialize a newly created [Request] to have the given [id] and [method]
/// name. If [params] is supplied, it is used as the "params" map for the
/// request. Otherwise an empty "params" map is allocated.
Request(this.id, this.method,
- [Map<String, Object> params, this.serverRequestTime])
+ [Map<String, Object>? params, this.serverRequestTime])
: params = params ?? <String, Object>{};
/// Return a request parsed from the given json, or `null` if the [data] is
@@ -114,18 +115,17 @@
var id = result[Request.ID];
var method = result[Request.METHOD];
if (id is! String || method is! String) {
- return null;
+ throw StateError('Unexpected type for id or method');
}
var time = result[Request.SERVER_REQUEST_TIME];
if (time != null && time is! int) {
- return null;
+ throw StateError('Unexpected type for server request time');
}
var params = result[Request.PARAMS];
if (params is Map || params == null) {
- return Request(id as String, method as String,
- params as Map<String, Object>, time as int);
+ return Request(id, method, params as Map<String, Object>?, time as int?);
} else {
- return null;
+ throw StateError('Unexpected type for params');
}
}
@@ -152,13 +152,14 @@
if (params.isNotEmpty) {
jsonObject[PARAMS] = params;
}
+ var serverRequestTime = this.serverRequestTime;
if (serverRequestTime != null) {
jsonObject[SERVER_REQUEST_TIME] = serverRequestTime;
}
return jsonObject;
}
- bool _equalLists(List first, List second) {
+ bool _equalLists(List? first, List? second) {
if (first == null) {
return second == null;
}
@@ -177,7 +178,7 @@
return true;
}
- bool _equalMaps(Map first, Map second) {
+ bool _equalMaps(Map? first, Map? second) {
if (first == null) {
return second == null;
}
@@ -198,7 +199,7 @@
return true;
}
- bool _equalObjects(Object first, Object second) {
+ bool _equalObjects(Object? first, Object? second) {
if (first == null) {
return second == null;
}
@@ -249,7 +250,7 @@
"Invalid parameter '$path'. $expectation.");
/// Return a request error representing an error that occurred in the plugin.
- static RequestError pluginError(dynamic exception, String stackTrace) =>
+ static RequestError pluginError(dynamic exception, String? stackTrace) =>
RequestError(RequestErrorCode.PLUGIN_ERROR, exception.toString(),
stackTrace: stackTrace);
@@ -296,49 +297,45 @@
/// The error that was caused by attempting to handle the request, or `null` if
/// there was no error.
- final RequestError error;
+ final RequestError? error;
/// The time at which the request was handled by the plugin.
final int requestTime;
/// A table mapping the names of result fields to their values. Should be
/// `null` if there is no result to send.
- Map<String, Object> result;
+ Map<String, Object>? result;
/// Initialize a newly created instance to represent a response to a request
/// with the given [id]. If [_result] is provided, it will be used as the
/// result; otherwise an empty result will be used. If an [error] is provided
/// then the response will represent an error condition.
- Response(this.id, this.requestTime, {this.error, Map<String, Object> result})
+ Response(this.id, this.requestTime, {this.error, Map<String, Object>? result})
: result = result;
/// Initialize a newly created instance based on the given JSON data.
factory Response.fromJson(Map json) {
- try {
- Object id = json[ID];
- if (id is! String) {
- return null;
- }
- Object error = json[ERROR];
- RequestError decodedError;
- if (error is Map) {
- decodedError =
- RequestError.fromJson(ResponseDecoder(null), '.error', error);
- }
- Object requestTime = json[REQUEST_TIME];
- if (requestTime is! int) {
- return null;
- }
- Object result = json[RESULT];
- Map<String, Object> decodedResult;
- if (result is Map) {
- decodedResult = result as Map<String, Object>;
- }
- return Response(id as String, requestTime as int,
- error: decodedError, result: decodedResult);
- } catch (exception) {
- return null;
+ var id = json[ID];
+ if (id is! String) {
+ throw StateError('Unexpected type for id');
}
+ var error = json[ERROR];
+ RequestError? decodedError;
+ if (error is Map) {
+ decodedError =
+ RequestError.fromJson(ResponseDecoder(null), '.error', error);
+ }
+ var requestTime = json[REQUEST_TIME];
+ if (requestTime is! int) {
+ throw StateError('Unexpected type for requestTime');
+ }
+ var result = json[RESULT];
+ Map<String, Object>? decodedResult;
+ if (result is Map) {
+ decodedResult = result as Map<String, Object>;
+ }
+ return Response(id, requestTime,
+ error: decodedError, result: decodedResult);
}
/// Return a table representing the structure of the Json object that will be
@@ -346,10 +343,12 @@
Map<String, Object> toJson() {
var jsonObject = <String, Object>{};
jsonObject[ID] = id;
+ var error = this.error;
if (error != null) {
jsonObject[ERROR] = error.toJson();
}
jsonObject[REQUEST_TIME] = requestTime;
+ var result = this.result;
if (result != null) {
jsonObject[RESULT] = result;
}
diff --git a/pkg/analyzer_plugin/lib/protocol/protocol_common.dart b/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
index 78e0b32..b22d06a 100644
--- a/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
+++ b/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
@@ -21,14 +21,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class AddContentOverlay implements HasToJson {
- String _content;
+ late String _content;
/// The new content of the file.
String get content => _content;
/// The new content of the file.
set content(String value) {
- assert(value != null);
_content = value;
}
@@ -37,7 +36,7 @@
}
factory AddContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
if (json['type'] != 'add') {
@@ -57,8 +56,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['type'] = 'add';
result['content'] = content;
return result;
@@ -100,30 +99,29 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisError implements HasToJson {
- AnalysisErrorSeverity _severity;
+ late AnalysisErrorSeverity _severity;
- AnalysisErrorType _type;
+ late AnalysisErrorType _type;
- Location _location;
+ late Location _location;
- String _message;
+ late String _message;
- String _correction;
+ String? _correction;
- String _code;
+ late String _code;
- String _url;
+ String? _url;
- List<DiagnosticMessage> _contextMessages;
+ List<DiagnosticMessage>? _contextMessages;
- bool _hasFix;
+ bool? _hasFix;
/// The severity of the error.
AnalysisErrorSeverity get severity => _severity;
/// The severity of the error.
set severity(AnalysisErrorSeverity value) {
- assert(value != null);
_severity = value;
}
@@ -132,7 +130,6 @@
/// The type of the error.
set type(AnalysisErrorType value) {
- assert(value != null);
_type = value;
}
@@ -141,7 +138,6 @@
/// The location associated with the error.
set location(Location value) {
- assert(value != null);
_location = value;
}
@@ -152,19 +148,18 @@
/// The message to be displayed for this error. The message should indicate
/// what is wrong with the code and why it is wrong.
set message(String value) {
- assert(value != null);
_message = value;
}
/// The correction message to be displayed for this error. The correction
/// message should indicate how the user can fix the error. The field is
/// omitted if there is no correction message associated with the error code.
- String get correction => _correction;
+ String? get correction => _correction;
/// The correction message to be displayed for this error. The correction
/// message should indicate how the user can fix the error. The field is
/// omitted if there is no correction message associated with the error code.
- set correction(String value) {
+ set correction(String? value) {
_correction = value;
}
@@ -173,25 +168,24 @@
/// The name, as a string, of the error code associated with this error.
set code(String value) {
- assert(value != null);
_code = value;
}
/// The URL of a page containing documentation associated with this error.
- String get url => _url;
+ String? get url => _url;
/// The URL of a page containing documentation associated with this error.
- set url(String value) {
+ set url(String? value) {
_url = value;
}
/// Additional messages associated with this diagnostic that provide context
/// to help the user understand the diagnostic.
- List<DiagnosticMessage> get contextMessages => _contextMessages;
+ List<DiagnosticMessage>? get contextMessages => _contextMessages;
/// Additional messages associated with this diagnostic that provide context
/// to help the user understand the diagnostic.
- set contextMessages(List<DiagnosticMessage> value) {
+ set contextMessages(List<DiagnosticMessage>? value) {
_contextMessages = value;
}
@@ -204,7 +198,7 @@
/// negatives, no false positives should be returned. If a client sees this
/// flag set they can proceed with the confidence that there are in fact
/// associated fixes.
- bool get hasFix => _hasFix;
+ bool? get hasFix => _hasFix;
/// A hint to indicate to interested clients that this error has an
/// associated fix (or fixes). The absence of this field implies there are
@@ -215,16 +209,16 @@
/// negatives, no false positives should be returned. If a client sees this
/// flag set they can proceed with the confidence that there are in fact
/// associated fixes.
- set hasFix(bool value) {
+ set hasFix(bool? value) {
_hasFix = value;
}
AnalysisError(AnalysisErrorSeverity severity, AnalysisErrorType type,
Location location, String message, String code,
- {String correction,
- String url,
- List<DiagnosticMessage> contextMessages,
- bool hasFix}) {
+ {String? correction,
+ String? url,
+ List<DiagnosticMessage>? contextMessages,
+ bool? hasFix}) {
this.severity = severity;
this.type = type;
this.location = location;
@@ -237,7 +231,7 @@
}
factory AnalysisError.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
AnalysisErrorSeverity severity;
@@ -268,7 +262,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'message');
}
- String correction;
+ String? correction;
if (json.containsKey('correction')) {
correction = jsonDecoder.decodeString(
jsonPath + '.correction', json['correction']);
@@ -279,19 +273,19 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'code');
}
- String url;
+ String? url;
if (json.containsKey('url')) {
url = jsonDecoder.decodeString(jsonPath + '.url', json['url']);
}
- List<DiagnosticMessage> contextMessages;
+ List<DiagnosticMessage>? contextMessages;
if (json.containsKey('contextMessages')) {
contextMessages = jsonDecoder.decodeList(
jsonPath + '.contextMessages',
json['contextMessages'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
DiagnosticMessage.fromJson(jsonDecoder, jsonPath, json));
}
- bool hasFix;
+ bool? hasFix;
if (json.containsKey('hasFix')) {
hasFix = jsonDecoder.decodeBool(jsonPath + '.hasFix', json['hasFix']);
}
@@ -306,24 +300,28 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['severity'] = severity.toJson();
result['type'] = type.toJson();
result['location'] = location.toJson();
result['message'] = message;
+ var correction = this.correction;
if (correction != null) {
result['correction'] = correction;
}
result['code'] = code;
+ var url = this.url;
if (url != null) {
result['url'] = url;
}
+ var contextMessages = this.contextMessages;
if (contextMessages != null) {
result['contextMessages'] = contextMessages
.map((DiagnosticMessage value) => value.toJson())
.toList();
}
+ var hasFix = this.hasFix;
if (hasFix != null) {
result['hasFix'] = hasFix;
}
@@ -408,7 +406,7 @@
}
factory AnalysisErrorSeverity.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return AnalysisErrorSeverity(json);
@@ -501,7 +499,7 @@
}
factory AnalysisErrorType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return AnalysisErrorType(json);
@@ -527,14 +525,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class ChangeContentOverlay implements HasToJson {
- List<SourceEdit> _edits;
+ late List<SourceEdit> _edits;
/// The edits to be applied to the file.
List<SourceEdit> get edits => _edits;
/// The edits to be applied to the file.
set edits(List<SourceEdit> value) {
- assert(value != null);
_edits = value;
}
@@ -543,7 +540,7 @@
}
factory ChangeContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
if (json['type'] != 'change') {
@@ -554,7 +551,7 @@
edits = jsonDecoder.decodeList(
jsonPath + '.edits',
json['edits'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
SourceEdit.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'edits');
@@ -566,8 +563,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['type'] = 'change';
result['edits'] = edits.map((SourceEdit value) => value.toJson()).toList();
return result;
@@ -624,58 +621,57 @@
///
/// Clients may not extend, implement or mix-in this class.
class CompletionSuggestion implements HasToJson {
- CompletionSuggestionKind _kind;
+ late CompletionSuggestionKind _kind;
- int _relevance;
+ late int _relevance;
- String _completion;
+ late String _completion;
- String _displayText;
+ String? _displayText;
- int _replacementOffset;
+ int? _replacementOffset;
- int _replacementLength;
+ int? _replacementLength;
- int _selectionOffset;
+ late int _selectionOffset;
- int _selectionLength;
+ late int _selectionLength;
- bool _isDeprecated;
+ late bool _isDeprecated;
- bool _isPotential;
+ late bool _isPotential;
- String _docSummary;
+ String? _docSummary;
- String _docComplete;
+ String? _docComplete;
- String _declaringType;
+ String? _declaringType;
- String _defaultArgumentListString;
+ String? _defaultArgumentListString;
- List<int> _defaultArgumentListTextRanges;
+ List<int>? _defaultArgumentListTextRanges;
- Element _element;
+ Element? _element;
- String _returnType;
+ String? _returnType;
- List<String> _parameterNames;
+ List<String>? _parameterNames;
- List<String> _parameterTypes;
+ List<String>? _parameterTypes;
- int _requiredParameterCount;
+ int? _requiredParameterCount;
- bool _hasNamedParameters;
+ bool? _hasNamedParameters;
- String _parameterName;
+ String? _parameterName;
- String _parameterType;
+ String? _parameterType;
/// The kind of element being suggested.
CompletionSuggestionKind get kind => _kind;
/// The kind of element being suggested.
set kind(CompletionSuggestionKind value) {
- assert(value != null);
_kind = value;
}
@@ -686,7 +682,6 @@
/// The relevance of this completion suggestion where a higher number
/// indicates a higher relevance.
set relevance(int value) {
- assert(value != null);
_relevance = value;
}
@@ -701,19 +696,18 @@
/// additionally insert a template for the parameters. The information
/// required in order to do so is contained in other fields.
set completion(String value) {
- assert(value != null);
_completion = value;
}
/// Text to be displayed in, for example, a completion pop-up. This field is
/// only defined if the displayed text should be different than the
/// completion. Otherwise it is omitted.
- String get displayText => _displayText;
+ String? get displayText => _displayText;
/// Text to be displayed in, for example, a completion pop-up. This field is
/// only defined if the displayed text should be different than the
/// completion. Otherwise it is omitted.
- set displayText(String value) {
+ set displayText(String? value) {
_displayText = value;
}
@@ -722,14 +716,14 @@
/// completion results. This value may be provided independently of
/// replacementLength (for example if only one differs from the completion
/// result value).
- int get replacementOffset => _replacementOffset;
+ int? get replacementOffset => _replacementOffset;
/// The offset of the start of the text to be replaced. If supplied, this
/// should be used in preference to the offset provided on the containing
/// completion results. This value may be provided independently of
/// replacementLength (for example if only one differs from the completion
/// result value).
- set replacementOffset(int value) {
+ set replacementOffset(int? value) {
_replacementOffset = value;
}
@@ -737,13 +731,13 @@
/// in preference to the offset provided on the containing completion
/// results. This value may be provided independently of replacementOffset
/// (for example if only one differs from the completion result value).
- int get replacementLength => _replacementLength;
+ int? get replacementLength => _replacementLength;
/// The length of the text to be replaced. If supplied, this should be used
/// in preference to the offset provided on the containing completion
/// results. This value may be provided independently of replacementOffset
/// (for example if only one differs from the completion result value).
- set replacementLength(int value) {
+ set replacementLength(int? value) {
_replacementLength = value;
}
@@ -754,7 +748,6 @@
/// The offset, relative to the beginning of the completion, of where the
/// selection should be placed after insertion.
set selectionOffset(int value) {
- assert(value != null);
_selectionOffset = value;
}
@@ -763,7 +756,6 @@
/// The number of characters that should be selected after insertion.
set selectionLength(int value) {
- assert(value != null);
_selectionLength = value;
}
@@ -772,7 +764,6 @@
/// True if the suggested element is deprecated.
set isDeprecated(bool value) {
- assert(value != null);
_isDeprecated = value;
}
@@ -783,49 +774,48 @@
/// True if the element is not known to be valid for the target. This happens
/// if the type of the target is dynamic.
set isPotential(bool value) {
- assert(value != null);
_isPotential = value;
}
/// An abbreviated version of the Dartdoc associated with the element being
/// suggested. This field is omitted if there is no Dartdoc associated with
/// the element.
- String get docSummary => _docSummary;
+ String? get docSummary => _docSummary;
/// An abbreviated version of the Dartdoc associated with the element being
/// suggested. This field is omitted if there is no Dartdoc associated with
/// the element.
- set docSummary(String value) {
+ set docSummary(String? value) {
_docSummary = value;
}
/// The Dartdoc associated with the element being suggested. This field is
/// omitted if there is no Dartdoc associated with the element.
- String get docComplete => _docComplete;
+ String? get docComplete => _docComplete;
/// The Dartdoc associated with the element being suggested. This field is
/// omitted if there is no Dartdoc associated with the element.
- set docComplete(String value) {
+ set docComplete(String? value) {
_docComplete = value;
}
/// The class that declares the element being suggested. This field is
/// omitted if the suggested element is not a member of a class.
- String get declaringType => _declaringType;
+ String? get declaringType => _declaringType;
/// The class that declares the element being suggested. This field is
/// omitted if the suggested element is not a member of a class.
- set declaringType(String value) {
+ set declaringType(String? value) {
_declaringType = value;
}
/// A default String for use in generating argument list source contents on
/// the client side.
- String get defaultArgumentListString => _defaultArgumentListString;
+ String? get defaultArgumentListString => _defaultArgumentListString;
/// A default String for use in generating argument list source contents on
/// the client side.
- set defaultArgumentListString(String value) {
+ set defaultArgumentListString(String? value) {
_defaultArgumentListString = value;
}
@@ -835,7 +825,8 @@
/// y', the corresponding text range [0, 1, 3, 1], indicates two text ranges
/// of length 1, starting at offsets 0 and 3. Clients can use these ranges to
/// treat the 'x' and 'y' values specially for linked edits.
- List<int> get defaultArgumentListTextRanges => _defaultArgumentListTextRanges;
+ List<int>? get defaultArgumentListTextRanges =>
+ _defaultArgumentListTextRanges;
/// Pairs of offsets and lengths describing 'defaultArgumentListString' text
/// ranges suitable for use by clients to set up linked edits of default
@@ -843,91 +834,91 @@
/// y', the corresponding text range [0, 1, 3, 1], indicates two text ranges
/// of length 1, starting at offsets 0 and 3. Clients can use these ranges to
/// treat the 'x' and 'y' values specially for linked edits.
- set defaultArgumentListTextRanges(List<int> value) {
+ set defaultArgumentListTextRanges(List<int>? value) {
_defaultArgumentListTextRanges = value;
}
/// Information about the element reference being suggested.
- Element get element => _element;
+ Element? get element => _element;
/// Information about the element reference being suggested.
- set element(Element value) {
+ set element(Element? value) {
_element = value;
}
/// The return type of the getter, function or method or the type of the
/// field being suggested. This field is omitted if the suggested element is
/// not a getter, function or method.
- String get returnType => _returnType;
+ String? get returnType => _returnType;
/// The return type of the getter, function or method or the type of the
/// field being suggested. This field is omitted if the suggested element is
/// not a getter, function or method.
- set returnType(String value) {
+ set returnType(String? value) {
_returnType = value;
}
/// The names of the parameters of the function or method being suggested.
/// This field is omitted if the suggested element is not a setter, function
/// or method.
- List<String> get parameterNames => _parameterNames;
+ List<String>? get parameterNames => _parameterNames;
/// The names of the parameters of the function or method being suggested.
/// This field is omitted if the suggested element is not a setter, function
/// or method.
- set parameterNames(List<String> value) {
+ set parameterNames(List<String>? value) {
_parameterNames = value;
}
/// The types of the parameters of the function or method being suggested.
/// This field is omitted if the parameterNames field is omitted.
- List<String> get parameterTypes => _parameterTypes;
+ List<String>? get parameterTypes => _parameterTypes;
/// The types of the parameters of the function or method being suggested.
/// This field is omitted if the parameterNames field is omitted.
- set parameterTypes(List<String> value) {
+ set parameterTypes(List<String>? value) {
_parameterTypes = value;
}
/// The number of required parameters for the function or method being
/// suggested. This field is omitted if the parameterNames field is omitted.
- int get requiredParameterCount => _requiredParameterCount;
+ int? get requiredParameterCount => _requiredParameterCount;
/// The number of required parameters for the function or method being
/// suggested. This field is omitted if the parameterNames field is omitted.
- set requiredParameterCount(int value) {
+ set requiredParameterCount(int? value) {
_requiredParameterCount = value;
}
/// True if the function or method being suggested has at least one named
/// parameter. This field is omitted if the parameterNames field is omitted.
- bool get hasNamedParameters => _hasNamedParameters;
+ bool? get hasNamedParameters => _hasNamedParameters;
/// True if the function or method being suggested has at least one named
/// parameter. This field is omitted if the parameterNames field is omitted.
- set hasNamedParameters(bool value) {
+ set hasNamedParameters(bool? value) {
_hasNamedParameters = value;
}
/// The name of the optional parameter being suggested. This field is omitted
/// if the suggestion is not the addition of an optional argument within an
/// argument list.
- String get parameterName => _parameterName;
+ String? get parameterName => _parameterName;
/// The name of the optional parameter being suggested. This field is omitted
/// if the suggestion is not the addition of an optional argument within an
/// argument list.
- set parameterName(String value) {
+ set parameterName(String? value) {
_parameterName = value;
}
/// The type of the options parameter being suggested. This field is omitted
/// if the parameterName field is omitted.
- String get parameterType => _parameterType;
+ String? get parameterType => _parameterType;
/// The type of the options parameter being suggested. This field is omitted
/// if the parameterName field is omitted.
- set parameterType(String value) {
+ set parameterType(String? value) {
_parameterType = value;
}
@@ -939,22 +930,22 @@
int selectionLength,
bool isDeprecated,
bool isPotential,
- {String displayText,
- int replacementOffset,
- int replacementLength,
- String docSummary,
- String docComplete,
- String declaringType,
- String defaultArgumentListString,
- List<int> defaultArgumentListTextRanges,
- Element element,
- String returnType,
- List<String> parameterNames,
- List<String> parameterTypes,
- int requiredParameterCount,
- bool hasNamedParameters,
- String parameterName,
- String parameterType}) {
+ {String? displayText,
+ int? replacementOffset,
+ int? replacementLength,
+ String? docSummary,
+ String? docComplete,
+ String? declaringType,
+ String? defaultArgumentListString,
+ List<int>? defaultArgumentListTextRanges,
+ Element? element,
+ String? returnType,
+ List<String>? parameterNames,
+ List<String>? parameterTypes,
+ int? requiredParameterCount,
+ bool? hasNamedParameters,
+ String? parameterName,
+ String? parameterType}) {
this.kind = kind;
this.relevance = relevance;
this.completion = completion;
@@ -981,7 +972,7 @@
}
factory CompletionSuggestion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
CompletionSuggestionKind kind;
@@ -1005,17 +996,17 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'completion');
}
- String displayText;
+ String? displayText;
if (json.containsKey('displayText')) {
displayText = jsonDecoder.decodeString(
jsonPath + '.displayText', json['displayText']);
}
- int replacementOffset;
+ int? replacementOffset;
if (json.containsKey('replacementOffset')) {
replacementOffset = jsonDecoder.decodeInt(
jsonPath + '.replacementOffset', json['replacementOffset']);
}
- int replacementLength;
+ int? replacementLength;
if (json.containsKey('replacementLength')) {
replacementLength = jsonDecoder.decodeInt(
jsonPath + '.replacementLength', json['replacementLength']);
@@ -1048,71 +1039,71 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'isPotential');
}
- String docSummary;
+ String? docSummary;
if (json.containsKey('docSummary')) {
docSummary = jsonDecoder.decodeString(
jsonPath + '.docSummary', json['docSummary']);
}
- String docComplete;
+ String? docComplete;
if (json.containsKey('docComplete')) {
docComplete = jsonDecoder.decodeString(
jsonPath + '.docComplete', json['docComplete']);
}
- String declaringType;
+ String? declaringType;
if (json.containsKey('declaringType')) {
declaringType = jsonDecoder.decodeString(
jsonPath + '.declaringType', json['declaringType']);
}
- String defaultArgumentListString;
+ String? defaultArgumentListString;
if (json.containsKey('defaultArgumentListString')) {
defaultArgumentListString = jsonDecoder.decodeString(
jsonPath + '.defaultArgumentListString',
json['defaultArgumentListString']);
}
- List<int> defaultArgumentListTextRanges;
+ List<int>? defaultArgumentListTextRanges;
if (json.containsKey('defaultArgumentListTextRanges')) {
defaultArgumentListTextRanges = jsonDecoder.decodeList(
jsonPath + '.defaultArgumentListTextRanges',
json['defaultArgumentListTextRanges'],
jsonDecoder.decodeInt);
}
- Element element;
+ Element? element;
if (json.containsKey('element')) {
element = Element.fromJson(
jsonDecoder, jsonPath + '.element', json['element']);
}
- String returnType;
+ String? returnType;
if (json.containsKey('returnType')) {
returnType = jsonDecoder.decodeString(
jsonPath + '.returnType', json['returnType']);
}
- List<String> parameterNames;
+ List<String>? parameterNames;
if (json.containsKey('parameterNames')) {
parameterNames = jsonDecoder.decodeList(jsonPath + '.parameterNames',
json['parameterNames'], jsonDecoder.decodeString);
}
- List<String> parameterTypes;
+ List<String>? parameterTypes;
if (json.containsKey('parameterTypes')) {
parameterTypes = jsonDecoder.decodeList(jsonPath + '.parameterTypes',
json['parameterTypes'], jsonDecoder.decodeString);
}
- int requiredParameterCount;
+ int? requiredParameterCount;
if (json.containsKey('requiredParameterCount')) {
requiredParameterCount = jsonDecoder.decodeInt(
jsonPath + '.requiredParameterCount',
json['requiredParameterCount']);
}
- bool hasNamedParameters;
+ bool? hasNamedParameters;
if (json.containsKey('hasNamedParameters')) {
hasNamedParameters = jsonDecoder.decodeBool(
jsonPath + '.hasNamedParameters', json['hasNamedParameters']);
}
- String parameterName;
+ String? parameterName;
if (json.containsKey('parameterName')) {
parameterName = jsonDecoder.decodeString(
jsonPath + '.parameterName', json['parameterName']);
}
- String parameterType;
+ String? parameterType;
if (json.containsKey('parameterType')) {
parameterType = jsonDecoder.decodeString(
jsonPath + '.parameterType', json['parameterType']);
@@ -1141,17 +1132,20 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['relevance'] = relevance;
result['completion'] = completion;
+ var displayText = this.displayText;
if (displayText != null) {
result['displayText'] = displayText;
}
+ var replacementOffset = this.replacementOffset;
if (replacementOffset != null) {
result['replacementOffset'] = replacementOffset;
}
+ var replacementLength = this.replacementLength;
if (replacementLength != null) {
result['replacementLength'] = replacementLength;
}
@@ -1159,42 +1153,55 @@
result['selectionLength'] = selectionLength;
result['isDeprecated'] = isDeprecated;
result['isPotential'] = isPotential;
+ var docSummary = this.docSummary;
if (docSummary != null) {
result['docSummary'] = docSummary;
}
+ var docComplete = this.docComplete;
if (docComplete != null) {
result['docComplete'] = docComplete;
}
+ var declaringType = this.declaringType;
if (declaringType != null) {
result['declaringType'] = declaringType;
}
+ var defaultArgumentListString = this.defaultArgumentListString;
if (defaultArgumentListString != null) {
result['defaultArgumentListString'] = defaultArgumentListString;
}
+ var defaultArgumentListTextRanges = this.defaultArgumentListTextRanges;
if (defaultArgumentListTextRanges != null) {
result['defaultArgumentListTextRanges'] = defaultArgumentListTextRanges;
}
+ var element = this.element;
if (element != null) {
result['element'] = element.toJson();
}
+ var returnType = this.returnType;
if (returnType != null) {
result['returnType'] = returnType;
}
+ var parameterNames = this.parameterNames;
if (parameterNames != null) {
result['parameterNames'] = parameterNames;
}
+ var parameterTypes = this.parameterTypes;
if (parameterTypes != null) {
result['parameterTypes'] = parameterTypes;
}
+ var requiredParameterCount = this.requiredParameterCount;
if (requiredParameterCount != null) {
result['requiredParameterCount'] = requiredParameterCount;
}
+ var hasNamedParameters = this.hasNamedParameters;
if (hasNamedParameters != null) {
result['hasNamedParameters'] = hasNamedParameters;
}
+ var parameterName = this.parameterName;
if (parameterName != null) {
result['parameterName'] = parameterName;
}
+ var parameterType = this.parameterType;
if (parameterType != null) {
result['parameterType'] = parameterType;
}
@@ -1380,7 +1387,7 @@
}
factory CompletionSuggestionKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return CompletionSuggestionKind(json);
@@ -1406,16 +1413,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class DiagnosticMessage implements HasToJson {
- String _message;
+ late String _message;
- Location _location;
+ late Location _location;
/// The message to be displayed to the user.
String get message => _message;
/// The message to be displayed to the user.
set message(String value) {
- assert(value != null);
_message = value;
}
@@ -1426,7 +1432,6 @@
/// The location associated with or referenced by the message. Clients should
/// provide the ability to navigate to the location.
set location(Location value) {
- assert(value != null);
_location = value;
}
@@ -1436,7 +1441,7 @@
}
factory DiagnosticMessage.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String message;
@@ -1460,8 +1465,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['message'] = message;
result['location'] = location.toJson();
return result;
@@ -1526,28 +1531,27 @@
return flags;
}
- ElementKind _kind;
+ late ElementKind _kind;
- String _name;
+ late String _name;
- Location _location;
+ Location? _location;
- int _flags;
+ late int _flags;
- String _parameters;
+ String? _parameters;
- String _returnType;
+ String? _returnType;
- String _typeParameters;
+ String? _typeParameters;
- String _aliasedType;
+ String? _aliasedType;
/// The kind of the element.
ElementKind get kind => _kind;
/// The kind of the element.
set kind(ElementKind value) {
- assert(value != null);
_kind = value;
}
@@ -1558,15 +1562,14 @@
/// The name of the element. This is typically used as the label in the
/// outline.
set name(String value) {
- assert(value != null);
_name = value;
}
/// The location of the name in the declaration of the element.
- Location get location => _location;
+ Location? get location => _location;
/// The location of the name in the declaration of the element.
- set location(Location value) {
+ set location(Location? value) {
_location = value;
}
@@ -1591,7 +1594,6 @@
/// - 0x10 - set if the element is private
/// - 0x20 - set if the element is deprecated
set flags(int value) {
- assert(value != null);
_flags = value;
}
@@ -1599,54 +1601,54 @@
/// function this field will not be defined. If the element doesn't have
/// parameters (e.g. getter), this field will not be defined. If the element
/// has zero parameters, this field will have a value of "()".
- String get parameters => _parameters;
+ String? get parameters => _parameters;
/// The parameter list for the element. If the element is not a method or
/// function this field will not be defined. If the element doesn't have
/// parameters (e.g. getter), this field will not be defined. If the element
/// has zero parameters, this field will have a value of "()".
- set parameters(String value) {
+ set parameters(String? value) {
_parameters = value;
}
/// The return type of the element. If the element is not a method or
/// function this field will not be defined. If the element does not have a
/// declared return type, this field will contain an empty string.
- String get returnType => _returnType;
+ String? get returnType => _returnType;
/// The return type of the element. If the element is not a method or
/// function this field will not be defined. If the element does not have a
/// declared return type, this field will contain an empty string.
- set returnType(String value) {
+ set returnType(String? value) {
_returnType = value;
}
/// The type parameter list for the element. If the element doesn't have type
/// parameters, this field will not be defined.
- String get typeParameters => _typeParameters;
+ String? get typeParameters => _typeParameters;
/// The type parameter list for the element. If the element doesn't have type
/// parameters, this field will not be defined.
- set typeParameters(String value) {
+ set typeParameters(String? value) {
_typeParameters = value;
}
/// If the element is a type alias, this field is the aliased type. Otherwise
/// this field will not be defined.
- String get aliasedType => _aliasedType;
+ String? get aliasedType => _aliasedType;
/// If the element is a type alias, this field is the aliased type. Otherwise
/// this field will not be defined.
- set aliasedType(String value) {
+ set aliasedType(String? value) {
_aliasedType = value;
}
Element(ElementKind kind, String name, int flags,
- {Location location,
- String parameters,
- String returnType,
- String typeParameters,
- String aliasedType}) {
+ {Location? location,
+ String? parameters,
+ String? returnType,
+ String? typeParameters,
+ String? aliasedType}) {
this.kind = kind;
this.name = name;
this.location = location;
@@ -1658,7 +1660,7 @@
}
factory Element.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
ElementKind kind;
@@ -1674,7 +1676,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'name');
}
- Location location;
+ Location? location;
if (json.containsKey('location')) {
location = Location.fromJson(
jsonDecoder, jsonPath + '.location', json['location']);
@@ -1685,22 +1687,22 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'flags');
}
- String parameters;
+ String? parameters;
if (json.containsKey('parameters')) {
parameters = jsonDecoder.decodeString(
jsonPath + '.parameters', json['parameters']);
}
- String returnType;
+ String? returnType;
if (json.containsKey('returnType')) {
returnType = jsonDecoder.decodeString(
jsonPath + '.returnType', json['returnType']);
}
- String typeParameters;
+ String? typeParameters;
if (json.containsKey('typeParameters')) {
typeParameters = jsonDecoder.decodeString(
jsonPath + '.typeParameters', json['typeParameters']);
}
- String aliasedType;
+ String? aliasedType;
if (json.containsKey('aliasedType')) {
aliasedType = jsonDecoder.decodeString(
jsonPath + '.aliasedType', json['aliasedType']);
@@ -1724,23 +1726,28 @@
bool get isDeprecated => (flags & FLAG_DEPRECATED) != 0;
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['name'] = name;
+ var location = this.location;
if (location != null) {
result['location'] = location.toJson();
}
result['flags'] = flags;
+ var parameters = this.parameters;
if (parameters != null) {
result['parameters'] = parameters;
}
+ var returnType = this.returnType;
if (returnType != null) {
result['returnType'] = returnType;
}
+ var typeParameters = this.typeParameters;
if (typeParameters != null) {
result['typeParameters'] = typeParameters;
}
+ var aliasedType = this.aliasedType;
if (aliasedType != null) {
result['aliasedType'] = aliasedType;
}
@@ -1975,7 +1982,7 @@
}
factory ElementKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return ElementKind(json);
@@ -2076,7 +2083,7 @@
}
factory FoldingKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return FoldingKind(json);
@@ -2103,18 +2110,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class FoldingRegion implements HasToJson {
- FoldingKind _kind;
+ late FoldingKind _kind;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
/// The kind of the region.
FoldingKind get kind => _kind;
/// The kind of the region.
set kind(FoldingKind value) {
- assert(value != null);
_kind = value;
}
@@ -2123,7 +2129,6 @@
/// The offset of the region to be folded.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2132,7 +2137,6 @@
/// The length of the region to be folded.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -2143,7 +2147,7 @@
}
factory FoldingRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
FoldingKind kind;
@@ -2172,8 +2176,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['offset'] = offset;
result['length'] = length;
@@ -2213,18 +2217,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class HighlightRegion implements HasToJson {
- HighlightRegionType _type;
+ late HighlightRegionType _type;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
/// The type of highlight associated with the region.
HighlightRegionType get type => _type;
/// The type of highlight associated with the region.
set type(HighlightRegionType value) {
- assert(value != null);
_type = value;
}
@@ -2233,7 +2236,6 @@
/// The offset of the region to be highlighted.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2242,7 +2244,6 @@
/// The length of the region to be highlighted.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -2253,7 +2254,7 @@
}
factory HighlightRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
HighlightRegionType type;
@@ -2282,8 +2283,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['type'] = type.toJson();
result['offset'] = offset;
result['length'] = length;
@@ -2860,7 +2861,7 @@
}
factory HighlightRegionType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return HighlightRegionType(json);
@@ -2889,38 +2890,37 @@
///
/// Clients may not extend, implement or mix-in this class.
class KytheEntry implements HasToJson {
- KytheVName _source;
+ late KytheVName _source;
- String _kind;
+ String? _kind;
- KytheVName _target;
+ KytheVName? _target;
- String _fact;
+ late String _fact;
- List<int> _value;
+ List<int>? _value;
/// The ticket of the source node.
KytheVName get source => _source;
/// The ticket of the source node.
set source(KytheVName value) {
- assert(value != null);
_source = value;
}
/// An edge label. The schema defines which labels are meaningful.
- String get kind => _kind;
+ String? get kind => _kind;
/// An edge label. The schema defines which labels are meaningful.
- set kind(String value) {
+ set kind(String? value) {
_kind = value;
}
/// The ticket of the target node.
- KytheVName get target => _target;
+ KytheVName? get target => _target;
/// The ticket of the target node.
- set target(KytheVName value) {
+ set target(KytheVName? value) {
_target = value;
}
@@ -2929,20 +2929,19 @@
/// A fact label. The schema defines which fact labels are meaningful.
set fact(String value) {
- assert(value != null);
_fact = value;
}
/// The String value of the fact.
- List<int> get value => _value;
+ List<int>? get value => _value;
/// The String value of the fact.
- set value(List<int> value) {
+ set value(List<int>? value) {
_value = value;
}
KytheEntry(KytheVName source, String fact,
- {String kind, KytheVName target, List<int> value}) {
+ {String? kind, KytheVName? target, List<int>? value}) {
this.source = source;
this.kind = kind;
this.target = target;
@@ -2951,7 +2950,7 @@
}
factory KytheEntry.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
KytheVName source;
@@ -2961,11 +2960,11 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'source');
}
- String kind;
+ String? kind;
if (json.containsKey('kind')) {
kind = jsonDecoder.decodeString(jsonPath + '.kind', json['kind']);
}
- KytheVName target;
+ KytheVName? target;
if (json.containsKey('target')) {
target = KytheVName.fromJson(
jsonDecoder, jsonPath + '.target', json['target']);
@@ -2976,7 +2975,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'fact');
}
- List<int> value;
+ List<int>? value;
if (json.containsKey('value')) {
value = jsonDecoder.decodeList(
jsonPath + '.value', json['value'], jsonDecoder.decodeInt);
@@ -2988,16 +2987,19 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['source'] = source.toJson();
+ var kind = this.kind;
if (kind != null) {
result['kind'] = kind;
}
+ var target = this.target;
if (target != null) {
result['target'] = target.toJson();
}
result['fact'] = fact;
+ var value = this.value;
if (value != null) {
result['value'] = value;
}
@@ -3043,22 +3045,21 @@
///
/// Clients may not extend, implement or mix-in this class.
class KytheVName implements HasToJson {
- String _signature;
+ late String _signature;
- String _corpus;
+ late String _corpus;
- String _root;
+ late String _root;
- String _path;
+ late String _path;
- String _language;
+ late String _language;
/// An opaque signature generated by the analyzer.
String get signature => _signature;
/// An opaque signature generated by the analyzer.
set signature(String value) {
- assert(value != null);
_signature = value;
}
@@ -3071,7 +3072,6 @@
/// is a collection of related files, such as the contents of a given source
/// repository.
set corpus(String value) {
- assert(value != null);
_corpus = value;
}
@@ -3084,7 +3084,6 @@
/// identifier, denoting a distinct subset of the corpus. This may also be
/// used to designate virtual collections like generated files.
set root(String value) {
- assert(value != null);
_root = value;
}
@@ -3095,7 +3094,6 @@
/// A path-structured label describing the “location” of the named object
/// relative to the corpus and the root.
set path(String value) {
- assert(value != null);
_path = value;
}
@@ -3104,7 +3102,6 @@
/// The language this name belongs to.
set language(String value) {
- assert(value != null);
_language = value;
}
@@ -3118,7 +3115,7 @@
}
factory KytheVName.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String signature;
@@ -3160,8 +3157,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['signature'] = signature;
result['corpus'] = corpus;
result['root'] = root;
@@ -3207,18 +3204,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class LinkedEditGroup implements HasToJson {
- List<Position> _positions;
+ late List<Position> _positions;
- int _length;
+ late int _length;
- List<LinkedEditSuggestion> _suggestions;
+ late List<LinkedEditSuggestion> _suggestions;
/// The positions of the regions that should be edited simultaneously.
List<Position> get positions => _positions;
/// The positions of the regions that should be edited simultaneously.
set positions(List<Position> value) {
- assert(value != null);
_positions = value;
}
@@ -3227,7 +3223,6 @@
/// The length of the regions that should be edited simultaneously.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -3238,7 +3233,6 @@
/// Pre-computed suggestions for what every region might want to be changed
/// to.
set suggestions(List<LinkedEditSuggestion> value) {
- assert(value != null);
_suggestions = value;
}
@@ -3250,7 +3244,7 @@
}
factory LinkedEditGroup.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<Position> positions;
@@ -3258,7 +3252,7 @@
positions = jsonDecoder.decodeList(
jsonPath + '.positions',
json['positions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
Position.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'positions');
@@ -3274,7 +3268,7 @@
suggestions = jsonDecoder.decodeList(
jsonPath + '.suggestions',
json['suggestions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
LinkedEditSuggestion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'suggestions');
@@ -3289,8 +3283,8 @@
LinkedEditGroup.empty() : this(<Position>[], 0, <LinkedEditSuggestion>[]);
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['positions'] =
positions.map((Position value) => value.toJson()).toList();
result['length'] = length;
@@ -3345,16 +3339,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class LinkedEditSuggestion implements HasToJson {
- String _value;
+ late String _value;
- LinkedEditSuggestionKind _kind;
+ late LinkedEditSuggestionKind _kind;
/// The value that could be used to replace all of the linked edit regions.
String get value => _value;
/// The value that could be used to replace all of the linked edit regions.
set value(String value) {
- assert(value != null);
_value = value;
}
@@ -3363,7 +3356,6 @@
/// The kind of value being proposed.
set kind(LinkedEditSuggestionKind value) {
- assert(value != null);
_kind = value;
}
@@ -3373,7 +3365,7 @@
}
factory LinkedEditSuggestion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String value;
@@ -3396,8 +3388,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['value'] = value;
result['kind'] = kind.toJson();
return result;
@@ -3470,7 +3462,7 @@
}
factory LinkedEditSuggestionKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return LinkedEditSuggestionKind(json);
@@ -3501,26 +3493,25 @@
///
/// Clients may not extend, implement or mix-in this class.
class Location implements HasToJson {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- int _startLine;
+ late int _startLine;
- int _startColumn;
+ late int _startColumn;
- int _endLine;
+ late int _endLine;
- int _endColumn;
+ late int _endColumn;
/// The file containing the range.
String get file => _file;
/// The file containing the range.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -3529,7 +3520,6 @@
/// The offset of the range.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -3538,7 +3528,6 @@
/// The length of the range.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -3549,7 +3538,6 @@
/// The one-based index of the line containing the first character of the
/// range.
set startLine(int value) {
- assert(value != null);
_startLine = value;
}
@@ -3560,7 +3548,6 @@
/// The one-based index of the column containing the first character of the
/// range.
set startColumn(int value) {
- assert(value != null);
_startColumn = value;
}
@@ -3571,7 +3558,6 @@
/// The one-based index of the line containing the character immediately
/// following the range.
set endLine(int value) {
- assert(value != null);
_endLine = value;
}
@@ -3582,7 +3568,6 @@
/// The one-based index of the column containing the character immediately
/// following the range.
set endColumn(int value) {
- assert(value != null);
_endColumn = value;
}
@@ -3598,7 +3583,7 @@
}
factory Location.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -3654,8 +3639,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
result['length'] = length;
@@ -3707,18 +3692,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class NavigationRegion implements HasToJson {
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- List<int> _targets;
+ late List<int> _targets;
/// The offset of the region from which the user can navigate.
int get offset => _offset;
/// The offset of the region from which the user can navigate.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -3727,7 +3711,6 @@
/// The length of the region from which the user can navigate.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -3740,7 +3723,6 @@
/// which the given region is bound. By opening the target, clients can
/// implement one form of navigation. This list cannot be empty.
set targets(List<int> value) {
- assert(value != null);
_targets = value;
}
@@ -3751,7 +3733,7 @@
}
factory NavigationRegion.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int offset;
@@ -3780,8 +3762,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['offset'] = offset;
result['length'] = length;
result['targets'] = targets;
@@ -3826,28 +3808,27 @@
///
/// Clients may not extend, implement or mix-in this class.
class NavigationTarget implements HasToJson {
- ElementKind _kind;
+ late ElementKind _kind;
- int _fileIndex;
+ late int _fileIndex;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- int _startLine;
+ late int _startLine;
- int _startColumn;
+ late int _startColumn;
- int _codeOffset;
+ int? _codeOffset;
- int _codeLength;
+ int? _codeLength;
/// The kind of the element.
ElementKind get kind => _kind;
/// The kind of the element.
set kind(ElementKind value) {
- assert(value != null);
_kind = value;
}
@@ -3858,7 +3839,6 @@
/// The index of the file (in the enclosing navigation response) to navigate
/// to.
set fileIndex(int value) {
- assert(value != null);
_fileIndex = value;
}
@@ -3867,7 +3847,6 @@
/// The offset of the name of the target to which the user can navigate.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -3876,7 +3855,6 @@
/// The length of the name of the target to which the user can navigate.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -3887,7 +3865,6 @@
/// The one-based index of the line containing the first character of the
/// name of the target.
set startLine(int value) {
- assert(value != null);
_startLine = value;
}
@@ -3898,29 +3875,28 @@
/// The one-based index of the column containing the first character of the
/// name of the target.
set startColumn(int value) {
- assert(value != null);
_startColumn = value;
}
/// The offset of the target code to which the user can navigate.
- int get codeOffset => _codeOffset;
+ int? get codeOffset => _codeOffset;
/// The offset of the target code to which the user can navigate.
- set codeOffset(int value) {
+ set codeOffset(int? value) {
_codeOffset = value;
}
/// The length of the target code to which the user can navigate.
- int get codeLength => _codeLength;
+ int? get codeLength => _codeLength;
/// The length of the target code to which the user can navigate.
- set codeLength(int value) {
+ set codeLength(int? value) {
_codeLength = value;
}
NavigationTarget(ElementKind kind, int fileIndex, int offset, int length,
int startLine, int startColumn,
- {int codeOffset, int codeLength}) {
+ {int? codeOffset, int? codeLength}) {
this.kind = kind;
this.fileIndex = fileIndex;
this.offset = offset;
@@ -3932,7 +3908,7 @@
}
factory NavigationTarget.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
ElementKind kind;
@@ -3975,12 +3951,12 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'startColumn');
}
- int codeOffset;
+ int? codeOffset;
if (json.containsKey('codeOffset')) {
codeOffset =
jsonDecoder.decodeInt(jsonPath + '.codeOffset', json['codeOffset']);
}
- int codeLength;
+ int? codeLength;
if (json.containsKey('codeLength')) {
codeLength =
jsonDecoder.decodeInt(jsonPath + '.codeLength', json['codeLength']);
@@ -3994,17 +3970,19 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['fileIndex'] = fileIndex;
result['offset'] = offset;
result['length'] = length;
result['startLine'] = startLine;
result['startColumn'] = startColumn;
+ var codeOffset = this.codeOffset;
if (codeOffset != null) {
result['codeOffset'] = codeOffset;
}
+ var codeLength = this.codeLength;
if (codeLength != null) {
result['codeLength'] = codeLength;
}
@@ -4054,18 +4032,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class Occurrences implements HasToJson {
- Element _element;
+ late Element _element;
- List<int> _offsets;
+ late List<int> _offsets;
- int _length;
+ late int _length;
/// The element that was referenced.
Element get element => _element;
/// The element that was referenced.
set element(Element value) {
- assert(value != null);
_element = value;
}
@@ -4074,7 +4051,6 @@
/// The offsets of the name of the referenced element within the file.
set offsets(List<int> value) {
- assert(value != null);
_offsets = value;
}
@@ -4083,7 +4059,6 @@
/// The length of the name of the referenced element.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -4094,7 +4069,7 @@
}
factory Occurrences.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
Element element;
@@ -4124,8 +4099,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['element'] = element.toJson();
result['offsets'] = offsets;
result['length'] = length;
@@ -4168,24 +4143,23 @@
///
/// Clients may not extend, implement or mix-in this class.
class Outline implements HasToJson {
- Element _element;
+ late Element _element;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- int _codeOffset;
+ late int _codeOffset;
- int _codeLength;
+ late int _codeLength;
- List<Outline> _children;
+ List<Outline>? _children;
/// A description of the element represented by this node.
Element get element => _element;
/// A description of the element represented by this node.
set element(Element value) {
- assert(value != null);
_element = value;
}
@@ -4200,7 +4174,6 @@
/// element. It can be used, for example, to map locations in the file back
/// to an outline.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -4209,7 +4182,6 @@
/// The length of the element.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -4220,7 +4192,6 @@
/// The offset of the first character of the element code, which is neither
/// documentation, nor annotation.
set codeOffset(int value) {
- assert(value != null);
_codeOffset = value;
}
@@ -4229,23 +4200,22 @@
/// The length of the element code.
set codeLength(int value) {
- assert(value != null);
_codeLength = value;
}
/// The children of the node. The field will be omitted if the node has no
/// children. Children are sorted by offset.
- List<Outline> get children => _children;
+ List<Outline>? get children => _children;
/// The children of the node. The field will be omitted if the node has no
/// children. Children are sorted by offset.
- set children(List<Outline> value) {
+ set children(List<Outline>? value) {
_children = value;
}
Outline(
Element element, int offset, int length, int codeOffset, int codeLength,
- {List<Outline> children}) {
+ {List<Outline>? children}) {
this.element = element;
this.offset = offset;
this.length = length;
@@ -4255,7 +4225,7 @@
}
factory Outline.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
Element element;
@@ -4291,12 +4261,12 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'codeLength');
}
- List<Outline> children;
+ List<Outline>? children;
if (json.containsKey('children')) {
children = jsonDecoder.decodeList(
jsonPath + '.children',
json['children'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
Outline.fromJson(jsonDecoder, jsonPath, json));
}
return Outline(element, offset, length, codeOffset, codeLength,
@@ -4307,13 +4277,14 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['element'] = element.toJson();
result['offset'] = offset;
result['length'] = length;
result['codeOffset'] = codeOffset;
result['codeLength'] = codeLength;
+ var children = this.children;
if (children != null) {
result['children'] =
children.map((Outline value) => value.toJson()).toList();
@@ -4361,20 +4332,19 @@
///
/// Clients may not extend, implement or mix-in this class.
class ParameterInfo implements HasToJson {
- ParameterKind _kind;
+ late ParameterKind _kind;
- String _name;
+ late String _name;
- String _type;
+ late String _type;
- String _defaultValue;
+ String? _defaultValue;
/// The kind of the parameter.
ParameterKind get kind => _kind;
/// The kind of the parameter.
set kind(ParameterKind value) {
- assert(value != null);
_kind = value;
}
@@ -4383,7 +4353,6 @@
/// The name of the parameter.
set name(String value) {
- assert(value != null);
_name = value;
}
@@ -4392,22 +4361,21 @@
/// The type of the parameter.
set type(String value) {
- assert(value != null);
_type = value;
}
/// The default value for this parameter. This value will be omitted if the
/// parameter does not have a default value.
- String get defaultValue => _defaultValue;
+ String? get defaultValue => _defaultValue;
/// The default value for this parameter. This value will be omitted if the
/// parameter does not have a default value.
- set defaultValue(String value) {
+ set defaultValue(String? value) {
_defaultValue = value;
}
ParameterInfo(ParameterKind kind, String name, String type,
- {String defaultValue}) {
+ {String? defaultValue}) {
this.kind = kind;
this.name = name;
this.type = type;
@@ -4415,7 +4383,7 @@
}
factory ParameterInfo.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
ParameterKind kind;
@@ -4437,7 +4405,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'type');
}
- String defaultValue;
+ String? defaultValue;
if (json.containsKey('defaultValue')) {
defaultValue = jsonDecoder.decodeString(
jsonPath + '.defaultValue', json['defaultValue']);
@@ -4449,11 +4417,12 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['name'] = name;
result['type'] = type;
+ var defaultValue = this.defaultValue;
if (defaultValue != null) {
result['defaultValue'] = defaultValue;
}
@@ -4538,7 +4507,7 @@
}
factory ParameterKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return ParameterKind(json);
@@ -4564,16 +4533,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class Position implements HasToJson {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
/// The file containing the position.
String get file => _file;
/// The file containing the position.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -4582,7 +4550,6 @@
/// The offset of the position.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -4592,7 +4559,7 @@
}
factory Position.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -4614,8 +4581,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
return result;
@@ -4725,7 +4692,7 @@
}
factory RefactoringKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return RefactoringKind(json);
@@ -4754,23 +4721,23 @@
///
/// Clients may not extend, implement or mix-in this class.
class RefactoringMethodParameter implements HasToJson {
- String _id;
+ String? _id;
- RefactoringMethodParameterKind _kind;
+ late RefactoringMethodParameterKind _kind;
- String _type;
+ late String _type;
- String _name;
+ late String _name;
- String _parameters;
+ String? _parameters;
/// The unique identifier of the parameter. Clients may omit this field for
/// the parameters they want to add.
- String get id => _id;
+ String? get id => _id;
/// The unique identifier of the parameter. Clients may omit this field for
/// the parameters they want to add.
- set id(String value) {
+ set id(String? value) {
_id = value;
}
@@ -4779,7 +4746,6 @@
/// The kind of the parameter.
set kind(RefactoringMethodParameterKind value) {
- assert(value != null);
_kind = value;
}
@@ -4790,7 +4756,6 @@
/// The type that should be given to the parameter, or the return type of the
/// parameter's function type.
set type(String value) {
- assert(value != null);
_type = value;
}
@@ -4799,25 +4764,24 @@
/// The name that should be given to the parameter.
set name(String value) {
- assert(value != null);
_name = value;
}
/// The parameter list of the parameter's function type. If the parameter is
/// not of a function type, this field will not be defined. If the function
/// type has zero parameters, this field will have a value of '()'.
- String get parameters => _parameters;
+ String? get parameters => _parameters;
/// The parameter list of the parameter's function type. If the parameter is
/// not of a function type, this field will not be defined. If the function
/// type has zero parameters, this field will have a value of '()'.
- set parameters(String value) {
+ set parameters(String? value) {
_parameters = value;
}
RefactoringMethodParameter(
RefactoringMethodParameterKind kind, String type, String name,
- {String id, String parameters}) {
+ {String? id, String? parameters}) {
this.id = id;
this.kind = kind;
this.type = type;
@@ -4826,10 +4790,10 @@
}
factory RefactoringMethodParameter.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
- String id;
+ String? id;
if (json.containsKey('id')) {
id = jsonDecoder.decodeString(jsonPath + '.id', json['id']);
}
@@ -4852,7 +4816,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'name');
}
- String parameters;
+ String? parameters;
if (json.containsKey('parameters')) {
parameters = jsonDecoder.decodeString(
jsonPath + '.parameters', json['parameters']);
@@ -4865,14 +4829,16 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
+ var id = this.id;
if (id != null) {
result['id'] = id;
}
result['kind'] = kind.toJson();
result['type'] = type;
result['name'] = name;
+ var parameters = this.parameters;
if (parameters != null) {
result['parameters'] = parameters;
}
@@ -4947,7 +4913,7 @@
}
factory RefactoringMethodParameterKind.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return RefactoringMethodParameterKind(json);
@@ -4975,18 +4941,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class RefactoringProblem implements HasToJson {
- RefactoringProblemSeverity _severity;
+ late RefactoringProblemSeverity _severity;
- String _message;
+ late String _message;
- Location _location;
+ Location? _location;
/// The severity of the problem being represented.
RefactoringProblemSeverity get severity => _severity;
/// The severity of the problem being represented.
set severity(RefactoringProblemSeverity value) {
- assert(value != null);
_severity = value;
}
@@ -4995,31 +4960,30 @@
/// A human-readable description of the problem being represented.
set message(String value) {
- assert(value != null);
_message = value;
}
/// The location of the problem being represented. This field is omitted
/// unless there is a specific location associated with the problem (such as
/// a location where an element being renamed will be shadowed).
- Location get location => _location;
+ Location? get location => _location;
/// The location of the problem being represented. This field is omitted
/// unless there is a specific location associated with the problem (such as
/// a location where an element being renamed will be shadowed).
- set location(Location value) {
+ set location(Location? value) {
_location = value;
}
RefactoringProblem(RefactoringProblemSeverity severity, String message,
- {Location location}) {
+ {Location? location}) {
this.severity = severity;
this.message = message;
this.location = location;
}
factory RefactoringProblem.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
RefactoringProblemSeverity severity;
@@ -5036,7 +5000,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'message');
}
- Location location;
+ Location? location;
if (json.containsKey('location')) {
location = Location.fromJson(
jsonDecoder, jsonPath + '.location', json['location']);
@@ -5048,10 +5012,11 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['severity'] = severity.toJson();
result['message'] = message;
+ var location = this.location;
if (location != null) {
result['location'] = location.toJson();
}
@@ -5145,7 +5110,7 @@
}
factory RefactoringProblemSeverity.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return RefactoringProblemSeverity(json);
@@ -5157,8 +5122,8 @@
}
/// Returns the [RefactoringProblemSeverity] with the maximal severity.
- static RefactoringProblemSeverity max(
- RefactoringProblemSeverity a, RefactoringProblemSeverity b) =>
+ static RefactoringProblemSeverity? max(
+ RefactoringProblemSeverity? a, RefactoringProblemSeverity? b) =>
maxRefactoringProblemSeverity(a, b);
@override
@@ -5178,7 +5143,7 @@
RemoveContentOverlay();
factory RemoveContentOverlay.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
if (json['type'] != 'remove') {
@@ -5191,8 +5156,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['type'] = 'remove';
return result;
}
@@ -5228,22 +5193,21 @@
///
/// Clients may not extend, implement or mix-in this class.
class SourceChange implements HasToJson {
- String _message;
+ late String _message;
- List<SourceFileEdit> _edits;
+ late List<SourceFileEdit> _edits;
- List<LinkedEditGroup> _linkedEditGroups;
+ late List<LinkedEditGroup> _linkedEditGroups;
- Position _selection;
+ Position? _selection;
- String _id;
+ String? _id;
/// A human-readable description of the change to be applied.
String get message => _message;
/// A human-readable description of the change to be applied.
set message(String value) {
- assert(value != null);
_message = value;
}
@@ -5252,7 +5216,6 @@
/// A list of the edits used to effect the change, grouped by file.
set edits(List<SourceFileEdit> value) {
- assert(value != null);
_edits = value;
}
@@ -5263,33 +5226,32 @@
/// A list of the linked editing groups used to customize the changes that
/// were made.
set linkedEditGroups(List<LinkedEditGroup> value) {
- assert(value != null);
_linkedEditGroups = value;
}
/// The position that should be selected after the edits have been applied.
- Position get selection => _selection;
+ Position? get selection => _selection;
/// The position that should be selected after the edits have been applied.
- set selection(Position value) {
+ set selection(Position? value) {
_selection = value;
}
/// The optional identifier of the change kind. The identifier remains stable
/// even if the message changes, or is parameterized.
- String get id => _id;
+ String? get id => _id;
/// The optional identifier of the change kind. The identifier remains stable
/// even if the message changes, or is parameterized.
- set id(String value) {
+ set id(String? value) {
_id = value;
}
SourceChange(String message,
- {List<SourceFileEdit> edits,
- List<LinkedEditGroup> linkedEditGroups,
- Position selection,
- String id}) {
+ {List<SourceFileEdit>? edits,
+ List<LinkedEditGroup>? linkedEditGroups,
+ Position? selection,
+ String? id}) {
this.message = message;
if (edits == null) {
this.edits = <SourceFileEdit>[];
@@ -5306,7 +5268,7 @@
}
factory SourceChange.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String message;
@@ -5321,7 +5283,7 @@
edits = jsonDecoder.decodeList(
jsonPath + '.edits',
json['edits'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
SourceFileEdit.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'edits');
@@ -5331,17 +5293,17 @@
linkedEditGroups = jsonDecoder.decodeList(
jsonPath + '.linkedEditGroups',
json['linkedEditGroups'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
LinkedEditGroup.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'linkedEditGroups');
}
- Position selection;
+ Position? selection;
if (json.containsKey('selection')) {
selection = Position.fromJson(
jsonDecoder, jsonPath + '.selection', json['selection']);
}
- String id;
+ String? id;
if (json.containsKey('id')) {
id = jsonDecoder.decodeString(jsonPath + '.id', json['id']);
}
@@ -5356,17 +5318,19 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['message'] = message;
result['edits'] =
edits.map((SourceFileEdit value) => value.toJson()).toList();
result['linkedEditGroups'] = linkedEditGroups
.map((LinkedEditGroup value) => value.toJson())
.toList();
+ var selection = this.selection;
if (selection != null) {
result['selection'] = selection.toJson();
}
+ var id = this.id;
if (id != null) {
result['id'] = id;
}
@@ -5388,7 +5352,7 @@
}
/// Returns the [FileEdit] for the given [file], maybe `null`.
- SourceFileEdit getFileEdit(String file) => getChangeFileEdit(this, file);
+ SourceFileEdit? getFileEdit(String file) => getChangeFileEdit(this, file);
@override
String toString() => json.encode(toJson());
@@ -5435,20 +5399,19 @@
static String applySequence(String code, Iterable<SourceEdit> edits) =>
applySequenceOfEdits(code, edits);
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- String _replacement;
+ late String _replacement;
- String _id;
+ String? _id;
/// The offset of the region to be modified.
int get offset => _offset;
/// The offset of the region to be modified.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -5457,7 +5420,6 @@
/// The length of the region to be modified.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -5466,7 +5428,6 @@
/// The code that is to replace the specified region in the original code.
set replacement(String value) {
- assert(value != null);
_replacement = value;
}
@@ -5478,7 +5439,7 @@
/// be appropriate (referred to as potential edits). Such edits will have an
/// id so that they can be referenced. Edits in the same response that do not
/// need to be referenced will not have an id.
- String get id => _id;
+ String? get id => _id;
/// An identifier that uniquely identifies this source edit from other edits
/// in the same response. This field is omitted unless a containing structure
@@ -5488,11 +5449,11 @@
/// be appropriate (referred to as potential edits). Such edits will have an
/// id so that they can be referenced. Edits in the same response that do not
/// need to be referenced will not have an id.
- set id(String value) {
+ set id(String? value) {
_id = value;
}
- SourceEdit(int offset, int length, String replacement, {String id}) {
+ SourceEdit(int offset, int length, String replacement, {String? id}) {
this.offset = offset;
this.length = length;
this.replacement = replacement;
@@ -5500,7 +5461,7 @@
}
factory SourceEdit.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int offset;
@@ -5522,7 +5483,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'replacement');
}
- String id;
+ String? id;
if (json.containsKey('id')) {
id = jsonDecoder.decodeString(jsonPath + '.id', json['id']);
}
@@ -5536,11 +5497,12 @@
int get end => offset + length;
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['offset'] = offset;
result['length'] = length;
result['replacement'] = replacement;
+ var id = this.id;
if (id != null) {
result['id'] = id;
}
@@ -5585,18 +5547,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class SourceFileEdit implements HasToJson {
- String _file;
+ late String _file;
- int _fileStamp;
+ late int _fileStamp;
- List<SourceEdit> _edits;
+ late List<SourceEdit> _edits;
/// The file containing the code to be modified.
String get file => _file;
/// The file containing the code to be modified.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -5613,7 +5574,6 @@
/// make sure that the file was not changed since then, so it is safe to
/// apply the change.
set fileStamp(int value) {
- assert(value != null);
_fileStamp = value;
}
@@ -5622,11 +5582,10 @@
/// A list of the edits used to effect the change.
set edits(List<SourceEdit> value) {
- assert(value != null);
_edits = value;
}
- SourceFileEdit(String file, int fileStamp, {List<SourceEdit> edits}) {
+ SourceFileEdit(String file, int fileStamp, {List<SourceEdit>? edits}) {
this.file = file;
this.fileStamp = fileStamp;
if (edits == null) {
@@ -5637,7 +5596,7 @@
}
factory SourceFileEdit.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -5658,7 +5617,7 @@
edits = jsonDecoder.decodeList(
jsonPath + '.edits',
json['edits'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
SourceEdit.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'edits');
@@ -5670,8 +5629,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['fileStamp'] = fileStamp;
result['edits'] = edits.map((SourceEdit value) => value.toJson()).toList();
diff --git a/pkg/analyzer_plugin/lib/protocol/protocol_generated.dart b/pkg/analyzer_plugin/lib/protocol/protocol_generated.dart
index 22b7fc2..8573286 100644
--- a/pkg/analyzer_plugin/lib/protocol/protocol_generated.dart
+++ b/pkg/analyzer_plugin/lib/protocol/protocol_generated.dart
@@ -22,16 +22,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisErrorFixes implements HasToJson {
- AnalysisError _error;
+ late AnalysisError _error;
- List<PrioritizedSourceChange> _fixes;
+ late List<PrioritizedSourceChange> _fixes;
/// The error with which the fixes are associated.
AnalysisError get error => _error;
/// The error with which the fixes are associated.
set error(AnalysisError value) {
- assert(value != null);
_error = value;
}
@@ -40,12 +39,11 @@
/// The fixes associated with the error.
set fixes(List<PrioritizedSourceChange> value) {
- assert(value != null);
_fixes = value;
}
AnalysisErrorFixes(AnalysisError error,
- {List<PrioritizedSourceChange> fixes}) {
+ {List<PrioritizedSourceChange>? fixes}) {
this.error = error;
if (fixes == null) {
this.fixes = <PrioritizedSourceChange>[];
@@ -55,7 +53,7 @@
}
factory AnalysisErrorFixes.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
AnalysisError error;
@@ -70,7 +68,7 @@
fixes = jsonDecoder.decodeList(
jsonPath + '.fixes',
json['fixes'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
PrioritizedSourceChange.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'fixes');
@@ -82,8 +80,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['error'] = error.toJson();
result['fixes'] =
fixes.map((PrioritizedSourceChange value) => value.toJson()).toList();
@@ -121,16 +119,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisErrorsParams implements HasToJson {
- String _file;
+ late String _file;
- List<AnalysisError> _errors;
+ late List<AnalysisError> _errors;
/// The file containing the errors.
String get file => _file;
/// The file containing the errors.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -139,7 +136,6 @@
/// The errors contained in the file.
set errors(List<AnalysisError> value) {
- assert(value != null);
_errors = value;
}
@@ -149,7 +145,7 @@
}
factory AnalysisErrorsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -163,7 +159,7 @@
errors = jsonDecoder.decodeList(
jsonPath + '.errors',
json['errors'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
AnalysisError.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'errors');
@@ -180,8 +176,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['errors'] =
errors.map((AnalysisError value) => value.toJson()).toList();
@@ -223,16 +219,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisFoldingParams implements HasToJson {
- String _file;
+ late String _file;
- List<FoldingRegion> _regions;
+ late List<FoldingRegion> _regions;
/// The file containing the folding regions.
String get file => _file;
/// The file containing the folding regions.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -241,7 +236,6 @@
/// The folding regions contained in the file.
set regions(List<FoldingRegion> value) {
- assert(value != null);
_regions = value;
}
@@ -251,7 +245,7 @@
}
factory AnalysisFoldingParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -265,7 +259,7 @@
regions = jsonDecoder.decodeList(
jsonPath + '.regions',
json['regions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
FoldingRegion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'regions');
@@ -282,8 +276,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['regions'] =
regions.map((FoldingRegion value) => value.toJson()).toList();
@@ -326,18 +320,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisGetNavigationParams implements RequestParams {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
/// The file in which navigation information is being requested.
String get file => _file;
/// The file in which navigation information is being requested.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -348,7 +341,6 @@
/// The offset of the region for which navigation information is being
/// requested.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -359,7 +351,6 @@
/// The length of the region for which navigation information is being
/// requested.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -370,7 +361,7 @@
}
factory AnalysisGetNavigationParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -404,8 +395,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
result['length'] = length;
@@ -450,11 +441,11 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisGetNavigationResult implements ResponseResult {
- List<String> _files;
+ late List<String> _files;
- List<NavigationTarget> _targets;
+ late List<NavigationTarget> _targets;
- List<NavigationRegion> _regions;
+ late List<NavigationRegion> _regions;
/// A list of the paths of files that are referenced by the navigation
/// targets.
@@ -463,7 +454,6 @@
/// A list of the paths of files that are referenced by the navigation
/// targets.
set files(List<String> value) {
- assert(value != null);
_files = value;
}
@@ -474,7 +464,6 @@
/// A list of the navigation targets that are referenced by the navigation
/// regions.
set targets(List<NavigationTarget> value) {
- assert(value != null);
_targets = value;
}
@@ -483,7 +472,6 @@
/// A list of the navigation regions within the requested region of the file.
set regions(List<NavigationRegion> value) {
- assert(value != null);
_regions = value;
}
@@ -495,7 +483,7 @@
}
factory AnalysisGetNavigationResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<String> files;
@@ -510,7 +498,7 @@
targets = jsonDecoder.decodeList(
jsonPath + '.targets',
json['targets'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
NavigationTarget.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'targets');
@@ -520,7 +508,7 @@
regions = jsonDecoder.decodeList(
jsonPath + '.regions',
json['regions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
NavigationRegion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'regions');
@@ -540,8 +528,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['files'] = files;
result['targets'] =
targets.map((NavigationTarget value) => value.toJson()).toList();
@@ -588,14 +576,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisHandleWatchEventsParams implements RequestParams {
- List<WatchEvent> _events;
+ late List<WatchEvent> _events;
/// The watch events that the plugin should handle.
List<WatchEvent> get events => _events;
/// The watch events that the plugin should handle.
set events(List<WatchEvent> value) {
- assert(value != null);
_events = value;
}
@@ -604,7 +591,7 @@
}
factory AnalysisHandleWatchEventsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<WatchEvent> events;
@@ -612,7 +599,7 @@
events = jsonDecoder.decodeList(
jsonPath + '.events',
json['events'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
WatchEvent.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'events');
@@ -630,8 +617,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['events'] =
events.map((WatchEvent value) => value.toJson()).toList();
return result;
@@ -667,7 +654,7 @@
/// Clients may not extend, implement or mix-in this class.
class AnalysisHandleWatchEventsResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -697,16 +684,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisHighlightsParams implements HasToJson {
- String _file;
+ late String _file;
- List<HighlightRegion> _regions;
+ late List<HighlightRegion> _regions;
/// The file containing the highlight regions.
String get file => _file;
/// The file containing the highlight regions.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -715,7 +701,6 @@
/// The highlight regions contained in the file.
set regions(List<HighlightRegion> value) {
- assert(value != null);
_regions = value;
}
@@ -725,7 +710,7 @@
}
factory AnalysisHighlightsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -739,7 +724,7 @@
regions = jsonDecoder.decodeList(
jsonPath + '.regions',
json['regions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
HighlightRegion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'regions');
@@ -756,8 +741,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['regions'] =
regions.map((HighlightRegion value) => value.toJson()).toList();
@@ -801,20 +786,19 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisNavigationParams implements HasToJson {
- String _file;
+ late String _file;
- List<NavigationRegion> _regions;
+ late List<NavigationRegion> _regions;
- List<NavigationTarget> _targets;
+ late List<NavigationTarget> _targets;
- List<String> _files;
+ late List<String> _files;
/// The file containing the navigation regions.
String get file => _file;
/// The file containing the navigation regions.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -823,7 +807,6 @@
/// The navigation regions contained in the file.
set regions(List<NavigationRegion> value) {
- assert(value != null);
_regions = value;
}
@@ -834,7 +817,6 @@
/// The navigation targets referenced in the file. They are referenced by
/// NavigationRegions by their index in this array.
set targets(List<NavigationTarget> value) {
- assert(value != null);
_targets = value;
}
@@ -845,7 +827,6 @@
/// The files containing navigation targets referenced in the file. They are
/// referenced by NavigationTargets by their index in this array.
set files(List<String> value) {
- assert(value != null);
_files = value;
}
@@ -858,7 +839,7 @@
}
factory AnalysisNavigationParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -872,7 +853,7 @@
regions = jsonDecoder.decodeList(
jsonPath + '.regions',
json['regions'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
NavigationRegion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'regions');
@@ -882,7 +863,7 @@
targets = jsonDecoder.decodeList(
jsonPath + '.targets',
json['targets'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
NavigationTarget.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'targets');
@@ -906,8 +887,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['regions'] =
regions.map((NavigationRegion value) => value.toJson()).toList();
@@ -957,16 +938,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisOccurrencesParams implements HasToJson {
- String _file;
+ late String _file;
- List<Occurrences> _occurrences;
+ late List<Occurrences> _occurrences;
/// The file in which the references occur.
String get file => _file;
/// The file in which the references occur.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -975,7 +955,6 @@
/// The occurrences of references to elements within the file.
set occurrences(List<Occurrences> value) {
- assert(value != null);
_occurrences = value;
}
@@ -985,7 +964,7 @@
}
factory AnalysisOccurrencesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -999,7 +978,7 @@
occurrences = jsonDecoder.decodeList(
jsonPath + '.occurrences',
json['occurrences'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
Occurrences.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'occurrences');
@@ -1017,8 +996,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['occurrences'] =
occurrences.map((Occurrences value) => value.toJson()).toList();
@@ -1060,16 +1039,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisOutlineParams implements HasToJson {
- String _file;
+ late String _file;
- List<Outline> _outline;
+ late List<Outline> _outline;
/// The file with which the outline is associated.
String get file => _file;
/// The file with which the outline is associated.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -1078,7 +1056,6 @@
/// The outline fragments associated with the file.
set outline(List<Outline> value) {
- assert(value != null);
_outline = value;
}
@@ -1088,7 +1065,7 @@
}
factory AnalysisOutlineParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -1102,7 +1079,7 @@
outline = jsonDecoder.decodeList(
jsonPath + '.outline',
json['outline'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
Outline.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'outline');
@@ -1119,8 +1096,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['outline'] = outline.map((Outline value) => value.toJson()).toList();
return result;
@@ -1204,7 +1181,7 @@
}
factory AnalysisService.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return AnalysisService(json);
@@ -1229,14 +1206,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetContextRootsParams implements RequestParams {
- List<ContextRoot> _roots;
+ late List<ContextRoot> _roots;
/// A list of the context roots that should be analyzed.
List<ContextRoot> get roots => _roots;
/// A list of the context roots that should be analyzed.
set roots(List<ContextRoot> value) {
- assert(value != null);
_roots = value;
}
@@ -1245,7 +1221,7 @@
}
factory AnalysisSetContextRootsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<ContextRoot> roots;
@@ -1253,7 +1229,7 @@
roots = jsonDecoder.decodeList(
jsonPath + '.roots',
json['roots'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
ContextRoot.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'roots');
@@ -1271,8 +1247,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['roots'] = roots.map((ContextRoot value) => value.toJson()).toList();
return result;
}
@@ -1307,7 +1283,7 @@
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetContextRootsResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -1336,14 +1312,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetPriorityFilesParams implements RequestParams {
- List<String> _files;
+ late List<String> _files;
/// The files that are to be a priority for analysis.
List<String> get files => _files;
/// The files that are to be a priority for analysis.
set files(List<String> value) {
- assert(value != null);
_files = value;
}
@@ -1352,7 +1327,7 @@
}
factory AnalysisSetPriorityFilesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<String> files;
@@ -1375,8 +1350,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['files'] = files;
return result;
}
@@ -1410,7 +1385,7 @@
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetPriorityFilesResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -1439,7 +1414,7 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetSubscriptionsParams implements RequestParams {
- Map<AnalysisService, List<String>> _subscriptions;
+ late Map<AnalysisService, List<String>> _subscriptions;
/// A table mapping services to a list of the files being subscribed to the
/// service.
@@ -1448,7 +1423,6 @@
/// A table mapping services to a list of the files being subscribed to the
/// service.
set subscriptions(Map<AnalysisService, List<String>> value) {
- assert(value != null);
_subscriptions = value;
}
@@ -1458,16 +1432,16 @@
}
factory AnalysisSetSubscriptionsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
Map<AnalysisService, List<String>> subscriptions;
if (json.containsKey('subscriptions')) {
subscriptions = jsonDecoder.decodeMap(
jsonPath + '.subscriptions', json['subscriptions'],
- keyDecoder: (String jsonPath, Object json) =>
+ keyDecoder: (String jsonPath, Object? json) =>
AnalysisService.fromJson(jsonDecoder, jsonPath, json),
- valueDecoder: (String jsonPath, Object json) => jsonDecoder
+ valueDecoder: (String jsonPath, Object? json) => jsonDecoder
.decodeList(jsonPath, json, jsonDecoder.decodeString));
} else {
throw jsonDecoder.mismatch(jsonPath, 'subscriptions');
@@ -1485,8 +1459,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['subscriptions'] = mapMap(subscriptions,
keyCallback: (AnalysisService value) => value.toJson());
return result;
@@ -1525,7 +1499,7 @@
/// Clients may not extend, implement or mix-in this class.
class AnalysisSetSubscriptionsResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -1554,38 +1528,37 @@
///
/// Clients may not extend, implement or mix-in this class.
class AnalysisUpdateContentParams implements RequestParams {
- Map<String, dynamic> _files;
+ late Map<String, Object> _files;
/// A table mapping the files whose content has changed to a description of
/// the content change.
- Map<String, dynamic> get files => _files;
+ Map<String, Object> get files => _files;
/// A table mapping the files whose content has changed to a description of
/// the content change.
- set files(Map<String, dynamic> value) {
- assert(value != null);
+ set files(Map<String, Object> value) {
_files = value;
}
- AnalysisUpdateContentParams(Map<String, dynamic> files) {
+ AnalysisUpdateContentParams(Map<String, Object> files) {
this.files = files;
}
factory AnalysisUpdateContentParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
- Map<String, dynamic> files;
+ Map<String, Object> files;
if (json.containsKey('files')) {
files = jsonDecoder.decodeMap(jsonPath + '.files', json['files'],
- valueDecoder: (String jsonPath, Object json) =>
+ valueDecoder: (String jsonPath, Object? json) =>
jsonDecoder.decodeUnion(jsonPath, json as Map, 'type', {
- 'add': (String jsonPath, Object json) =>
+ 'add': (String jsonPath, Object? json) =>
AddContentOverlay.fromJson(jsonDecoder, jsonPath, json),
- 'change': (String jsonPath, Object json) =>
+ 'change': (String jsonPath, Object? json) =>
ChangeContentOverlay.fromJson(
jsonDecoder, jsonPath, json),
- 'remove': (String jsonPath, Object json) =>
+ 'remove': (String jsonPath, Object? json) =>
RemoveContentOverlay.fromJson(jsonDecoder, jsonPath, json)
}));
} else {
@@ -1604,10 +1577,10 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
- result['files'] =
- mapMap(files, valueCallback: (dynamic value) => value.toJson());
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
+ result['files'] = mapMap(files,
+ valueCallback: (Object value) => (value as dynamic).toJson());
return result;
}
@@ -1622,7 +1595,7 @@
@override
bool operator ==(other) {
if (other is AnalysisUpdateContentParams) {
- return mapEqual(files, other.files, (dynamic a, dynamic b) => a == b);
+ return mapEqual(files, other.files, (Object a, Object b) => a == b);
}
return false;
}
@@ -1640,7 +1613,7 @@
/// Clients may not extend, implement or mix-in this class.
class AnalysisUpdateContentResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -1670,16 +1643,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class CompletionGetSuggestionsParams implements RequestParams {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
/// The file containing the point at which suggestions are to be made.
String get file => _file;
/// The file containing the point at which suggestions are to be made.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -1688,7 +1660,6 @@
/// The offset within the file at which suggestions are to be made.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -1698,7 +1669,7 @@
}
factory CompletionGetSuggestionsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -1726,8 +1697,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
return result;
@@ -1768,11 +1739,11 @@
///
/// Clients may not extend, implement or mix-in this class.
class CompletionGetSuggestionsResult implements ResponseResult {
- int _replacementOffset;
+ late int _replacementOffset;
- int _replacementLength;
+ late int _replacementLength;
- List<CompletionSuggestion> _results;
+ late List<CompletionSuggestion> _results;
/// The offset of the start of the text to be replaced. This will be
/// different than the offset used to request the completion suggestions if
@@ -1787,7 +1758,6 @@
/// particular, the replacementOffset will be the offset of the beginning of
/// said identifier.
set replacementOffset(int value) {
- assert(value != null);
_replacementOffset = value;
}
@@ -1800,7 +1770,6 @@
/// containing the cursor is to be replaced when the suggestion is applied
/// (that is, the number of characters in the existing identifier).
set replacementLength(int value) {
- assert(value != null);
_replacementLength = value;
}
@@ -1817,7 +1786,6 @@
/// client to respond to further keystrokes from the user without having to
/// make additional requests.
set results(List<CompletionSuggestion> value) {
- assert(value != null);
_results = value;
}
@@ -1829,7 +1797,7 @@
}
factory CompletionGetSuggestionsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int replacementOffset;
@@ -1851,7 +1819,7 @@
results = jsonDecoder.decodeList(
jsonPath + '.results',
json['results'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
CompletionSuggestion.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'results');
@@ -1872,8 +1840,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['replacementOffset'] = replacementOffset;
result['replacementLength'] = replacementLength;
result['results'] =
@@ -1920,11 +1888,11 @@
///
/// Clients may not extend, implement or mix-in this class.
class ContextRoot implements HasToJson {
- String _root;
+ late String _root;
- List<String> _exclude;
+ late List<String> _exclude;
- String _optionsFile;
+ String? _optionsFile;
/// The absolute path of the root directory containing the files to be
/// analyzed.
@@ -1933,7 +1901,6 @@
/// The absolute path of the root directory containing the files to be
/// analyzed.
set root(String value) {
- assert(value != null);
_root = value;
}
@@ -1944,28 +1911,27 @@
/// A list of the absolute paths of files and directories within the root
/// directory that should not be analyzed.
set exclude(List<String> value) {
- assert(value != null);
_exclude = value;
}
/// The absolute path of the analysis options file that should be used to
/// control the analysis of the files in the context.
- String get optionsFile => _optionsFile;
+ String? get optionsFile => _optionsFile;
/// The absolute path of the analysis options file that should be used to
/// control the analysis of the files in the context.
- set optionsFile(String value) {
+ set optionsFile(String? value) {
_optionsFile = value;
}
- ContextRoot(String root, List<String> exclude, {String optionsFile}) {
+ ContextRoot(String root, List<String> exclude, {String? optionsFile}) {
this.root = root;
this.exclude = exclude;
this.optionsFile = optionsFile;
}
factory ContextRoot.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String root;
@@ -1981,7 +1947,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'exclude');
}
- String optionsFile;
+ String? optionsFile;
if (json.containsKey('optionsFile')) {
optionsFile = jsonDecoder.decodeString(
jsonPath + '.optionsFile', json['optionsFile']);
@@ -1993,10 +1959,11 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['root'] = root;
result['exclude'] = exclude;
+ var optionsFile = this.optionsFile;
if (optionsFile != null) {
result['optionsFile'] = optionsFile;
}
@@ -2112,18 +2079,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetAssistsParams implements RequestParams {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
/// The file containing the code for which assists are being requested.
String get file => _file;
/// The file containing the code for which assists are being requested.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -2132,7 +2098,6 @@
/// The offset of the code for which assists are being requested.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2141,7 +2106,6 @@
/// The length of the code for which assists are being requested.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -2152,7 +2116,7 @@
}
factory EditGetAssistsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -2185,8 +2149,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
result['length'] = length;
@@ -2229,14 +2193,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetAssistsResult implements ResponseResult {
- List<PrioritizedSourceChange> _assists;
+ late List<PrioritizedSourceChange> _assists;
/// The assists that are available at the given location.
List<PrioritizedSourceChange> get assists => _assists;
/// The assists that are available at the given location.
set assists(List<PrioritizedSourceChange> value) {
- assert(value != null);
_assists = value;
}
@@ -2245,7 +2208,7 @@
}
factory EditGetAssistsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<PrioritizedSourceChange> assists;
@@ -2253,7 +2216,7 @@
assists = jsonDecoder.decodeList(
jsonPath + '.assists',
json['assists'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
PrioritizedSourceChange.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'assists');
@@ -2272,8 +2235,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['assists'] =
assists.map((PrioritizedSourceChange value) => value.toJson()).toList();
return result;
@@ -2314,18 +2277,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetAvailableRefactoringsParams implements RequestParams {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
/// The file containing the code on which the refactoring would be based.
String get file => _file;
/// The file containing the code on which the refactoring would be based.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -2334,7 +2296,6 @@
/// The offset of the code on which the refactoring would be based.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2343,7 +2304,6 @@
/// The length of the code on which the refactoring would be based.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -2354,7 +2314,7 @@
}
factory EditGetAvailableRefactoringsParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -2388,8 +2348,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
result['length'] = length;
@@ -2432,7 +2392,7 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetAvailableRefactoringsResult implements ResponseResult {
- List<RefactoringKind> _kinds;
+ late List<RefactoringKind> _kinds;
/// The kinds of refactorings that are valid for the given selection.
///
@@ -2449,7 +2409,6 @@
/// However, plugins can support pre-defined refactorings, such as a rename
/// refactoring, at locations not supported by server.
set kinds(List<RefactoringKind> value) {
- assert(value != null);
_kinds = value;
}
@@ -2458,7 +2417,7 @@
}
factory EditGetAvailableRefactoringsResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<RefactoringKind> kinds;
@@ -2466,7 +2425,7 @@
kinds = jsonDecoder.decodeList(
jsonPath + '.kinds',
json['kinds'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringKind.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'kinds');
@@ -2486,8 +2445,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kinds'] =
kinds.map((RefactoringKind value) => value.toJson()).toList();
return result;
@@ -2527,16 +2486,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetFixesParams implements RequestParams {
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
/// The file containing the errors for which fixes are being requested.
String get file => _file;
/// The file containing the errors for which fixes are being requested.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -2545,7 +2503,6 @@
/// The offset used to select the errors for which fixes will be returned.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2555,7 +2512,7 @@
}
factory EditGetFixesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -2582,8 +2539,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
result['offset'] = offset;
return result;
@@ -2622,14 +2579,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetFixesResult implements ResponseResult {
- List<AnalysisErrorFixes> _fixes;
+ late List<AnalysisErrorFixes> _fixes;
/// The fixes that are available for the errors at the given offset.
List<AnalysisErrorFixes> get fixes => _fixes;
/// The fixes that are available for the errors at the given offset.
set fixes(List<AnalysisErrorFixes> value) {
- assert(value != null);
_fixes = value;
}
@@ -2638,7 +2594,7 @@
}
factory EditGetFixesResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<AnalysisErrorFixes> fixes;
@@ -2646,7 +2602,7 @@
fixes = jsonDecoder.decodeList(
jsonPath + '.fixes',
json['fixes'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
AnalysisErrorFixes.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'fixes');
@@ -2665,8 +2621,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['fixes'] =
fixes.map((AnalysisErrorFixes value) => value.toJson()).toList();
return result;
@@ -2710,24 +2666,23 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetRefactoringParams implements RequestParams {
- RefactoringKind _kind;
+ late RefactoringKind _kind;
- String _file;
+ late String _file;
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- bool _validateOnly;
+ late bool _validateOnly;
- RefactoringOptions _options;
+ RefactoringOptions? _options;
/// The kind of refactoring to be performed.
RefactoringKind get kind => _kind;
/// The kind of refactoring to be performed.
set kind(RefactoringKind value) {
- assert(value != null);
_kind = value;
}
@@ -2736,7 +2691,6 @@
/// The file containing the code involved in the refactoring.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -2745,7 +2699,6 @@
/// The offset of the region involved in the refactoring.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -2754,7 +2707,6 @@
/// The length of the region involved in the refactoring.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -2765,7 +2717,6 @@
/// True if the client is only requesting that the values of the options be
/// validated and no change be generated.
set validateOnly(bool value) {
- assert(value != null);
_validateOnly = value;
}
@@ -2774,20 +2725,20 @@
/// that is expected is documented in the section titled Refactorings,
/// labeled as "Options". This field can be omitted if the refactoring does
/// not require any options or if the values of those options are not known.
- RefactoringOptions get options => _options;
+ RefactoringOptions? get options => _options;
/// Data used to provide values provided by the user. The structure of the
/// data is dependent on the kind of refactoring being performed. The data
/// that is expected is documented in the section titled Refactorings,
/// labeled as "Options". This field can be omitted if the refactoring does
/// not require any options or if the values of those options are not known.
- set options(RefactoringOptions value) {
+ set options(RefactoringOptions? value) {
_options = value;
}
EditGetRefactoringParams(RefactoringKind kind, String file, int offset,
int length, bool validateOnly,
- {RefactoringOptions options}) {
+ {RefactoringOptions? options}) {
this.kind = kind;
this.file = file;
this.offset = offset;
@@ -2797,7 +2748,7 @@
}
factory EditGetRefactoringParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
RefactoringKind kind;
@@ -2832,7 +2783,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'validateOnly');
}
- RefactoringOptions options;
+ RefactoringOptions? options;
if (json.containsKey('options')) {
options = RefactoringOptions.fromJson(
jsonDecoder, jsonPath + '.options', json['options'], kind);
@@ -2852,13 +2803,14 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['kind'] = kind.toJson();
result['file'] = file;
result['offset'] = offset;
result['length'] = length;
result['validateOnly'] = validateOnly;
+ var options = this.options;
if (options != null) {
result['options'] = options.toJson();
}
@@ -2912,17 +2864,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class EditGetRefactoringResult implements ResponseResult {
- List<RefactoringProblem> _initialProblems;
+ late List<RefactoringProblem> _initialProblems;
- List<RefactoringProblem> _optionsProblems;
+ late List<RefactoringProblem> _optionsProblems;
- List<RefactoringProblem> _finalProblems;
+ late List<RefactoringProblem> _finalProblems;
- RefactoringFeedback _feedback;
+ RefactoringFeedback? _feedback;
- SourceChange _change;
+ SourceChange? _change;
- List<String> _potentialEdits;
+ List<String>? _potentialEdits;
/// The initial status of the refactoring, that is, problems related to the
/// context in which the refactoring is requested. The list should be empty
@@ -2933,7 +2885,6 @@
/// context in which the refactoring is requested. The list should be empty
/// if there are no known problems.
set initialProblems(List<RefactoringProblem> value) {
- assert(value != null);
_initialProblems = value;
}
@@ -2946,7 +2897,6 @@
/// such as light-weight validation of a new name, flags compatibility, etc.
/// The list should be empty if there are no known problems.
set optionsProblems(List<RefactoringProblem> value) {
- assert(value != null);
_optionsProblems = value;
}
@@ -2959,7 +2909,6 @@
/// result of a full, potentially expensive validation and / or change
/// creation. The list should be empty if there are no known problems.
set finalProblems(List<RefactoringProblem> value) {
- assert(value != null);
_finalProblems = value;
}
@@ -2967,13 +2916,13 @@
/// dependent on the kind of refactoring being created. The data that is
/// returned is documented in the section titled Refactorings, labeled as
/// "Feedback".
- RefactoringFeedback get feedback => _feedback;
+ RefactoringFeedback? get feedback => _feedback;
/// Data used to provide feedback to the user. The structure of the data is
/// dependent on the kind of refactoring being created. The data that is
/// returned is documented in the section titled Refactorings, labeled as
/// "Feedback".
- set feedback(RefactoringFeedback value) {
+ set feedback(RefactoringFeedback? value) {
_feedback = value;
}
@@ -2981,13 +2930,13 @@
/// can be omitted if there are problems that prevent a set of changes from
/// being computed, such as having no options specified for a refactoring
/// that requires them, or if only validation was requested.
- SourceChange get change => _change;
+ SourceChange? get change => _change;
/// The changes that are to be applied to affect the refactoring. This field
/// can be omitted if there are problems that prevent a set of changes from
/// being computed, such as having no options specified for a refactoring
/// that requires them, or if only validation was requested.
- set change(SourceChange value) {
+ set change(SourceChange? value) {
_change = value;
}
@@ -2997,7 +2946,7 @@
/// modified, such as when a member is being renamed and there is a reference
/// to a member from an unknown type. This field can be omitted if the change
/// field is omitted or if there are no potential edits for the refactoring.
- List<String> get potentialEdits => _potentialEdits;
+ List<String>? get potentialEdits => _potentialEdits;
/// The ids of source edits that are not known to be valid. An edit is not
/// known to be valid if there was insufficient type information for the
@@ -3005,7 +2954,7 @@
/// modified, such as when a member is being renamed and there is a reference
/// to a member from an unknown type. This field can be omitted if the change
/// field is omitted or if there are no potential edits for the refactoring.
- set potentialEdits(List<String> value) {
+ set potentialEdits(List<String>? value) {
_potentialEdits = value;
}
@@ -3013,9 +2962,9 @@
List<RefactoringProblem> initialProblems,
List<RefactoringProblem> optionsProblems,
List<RefactoringProblem> finalProblems,
- {RefactoringFeedback feedback,
- SourceChange change,
- List<String> potentialEdits}) {
+ {RefactoringFeedback? feedback,
+ SourceChange? change,
+ List<String>? potentialEdits}) {
this.initialProblems = initialProblems;
this.optionsProblems = optionsProblems;
this.finalProblems = finalProblems;
@@ -3025,7 +2974,7 @@
}
factory EditGetRefactoringResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<RefactoringProblem> initialProblems;
@@ -3033,7 +2982,7 @@
initialProblems = jsonDecoder.decodeList(
jsonPath + '.initialProblems',
json['initialProblems'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'initialProblems');
@@ -3043,7 +2992,7 @@
optionsProblems = jsonDecoder.decodeList(
jsonPath + '.optionsProblems',
json['optionsProblems'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'optionsProblems');
@@ -3053,22 +3002,22 @@
finalProblems = jsonDecoder.decodeList(
jsonPath + '.finalProblems',
json['finalProblems'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringProblem.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'finalProblems');
}
- RefactoringFeedback feedback;
+ RefactoringFeedback? feedback;
if (json.containsKey('feedback')) {
feedback = RefactoringFeedback.fromJson(
jsonDecoder, jsonPath + '.feedback', json['feedback'], json);
}
- SourceChange change;
+ SourceChange? change;
if (json.containsKey('change')) {
change = SourceChange.fromJson(
jsonDecoder, jsonPath + '.change', json['change']);
}
- List<String> potentialEdits;
+ List<String>? potentialEdits;
if (json.containsKey('potentialEdits')) {
potentialEdits = jsonDecoder.decodeList(jsonPath + '.potentialEdits',
json['potentialEdits'], jsonDecoder.decodeString);
@@ -3089,8 +3038,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['initialProblems'] = initialProblems
.map((RefactoringProblem value) => value.toJson())
.toList();
@@ -3100,12 +3049,15 @@
result['finalProblems'] = finalProblems
.map((RefactoringProblem value) => value.toJson())
.toList();
+ var feedback = this.feedback;
if (feedback != null) {
result['feedback'] = feedback.toJson();
}
+ var change = this.change;
if (change != null) {
result['change'] = change.toJson();
}
+ var potentialEdits = this.potentialEdits;
if (potentialEdits != null) {
result['potentialEdits'] = potentialEdits;
}
@@ -3162,33 +3114,33 @@
///
/// Clients may not extend, implement or mix-in this class.
class ExtractLocalVariableFeedback extends RefactoringFeedback {
- List<int> _coveringExpressionOffsets;
+ List<int>? _coveringExpressionOffsets;
- List<int> _coveringExpressionLengths;
+ List<int>? _coveringExpressionLengths;
- List<String> _names;
+ late List<String> _names;
- List<int> _offsets;
+ late List<int> _offsets;
- List<int> _lengths;
+ late List<int> _lengths;
/// The offsets of the expressions that cover the specified selection, from
/// the down most to the up most.
- List<int> get coveringExpressionOffsets => _coveringExpressionOffsets;
+ List<int>? get coveringExpressionOffsets => _coveringExpressionOffsets;
/// The offsets of the expressions that cover the specified selection, from
/// the down most to the up most.
- set coveringExpressionOffsets(List<int> value) {
+ set coveringExpressionOffsets(List<int>? value) {
_coveringExpressionOffsets = value;
}
/// The lengths of the expressions that cover the specified selection, from
/// the down most to the up most.
- List<int> get coveringExpressionLengths => _coveringExpressionLengths;
+ List<int>? get coveringExpressionLengths => _coveringExpressionLengths;
/// The lengths of the expressions that cover the specified selection, from
/// the down most to the up most.
- set coveringExpressionLengths(List<int> value) {
+ set coveringExpressionLengths(List<int>? value) {
_coveringExpressionLengths = value;
}
@@ -3197,7 +3149,6 @@
/// The proposed names for the local variable.
set names(List<String> value) {
- assert(value != null);
_names = value;
}
@@ -3208,7 +3159,6 @@
/// The offsets of the expressions that would be replaced by a reference to
/// the variable.
set offsets(List<int> value) {
- assert(value != null);
_offsets = value;
}
@@ -3223,14 +3173,13 @@
/// a given expression, if the offset of that expression is offsets[i], then
/// the length of that expression is lengths[i].
set lengths(List<int> value) {
- assert(value != null);
_lengths = value;
}
ExtractLocalVariableFeedback(
List<String> names, List<int> offsets, List<int> lengths,
- {List<int> coveringExpressionOffsets,
- List<int> coveringExpressionLengths}) {
+ {List<int>? coveringExpressionOffsets,
+ List<int>? coveringExpressionLengths}) {
this.coveringExpressionOffsets = coveringExpressionOffsets;
this.coveringExpressionLengths = coveringExpressionLengths;
this.names = names;
@@ -3239,17 +3188,17 @@
}
factory ExtractLocalVariableFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
- List<int> coveringExpressionOffsets;
+ List<int>? coveringExpressionOffsets;
if (json.containsKey('coveringExpressionOffsets')) {
coveringExpressionOffsets = jsonDecoder.decodeList(
jsonPath + '.coveringExpressionOffsets',
json['coveringExpressionOffsets'],
jsonDecoder.decodeInt);
}
- List<int> coveringExpressionLengths;
+ List<int>? coveringExpressionLengths;
if (json.containsKey('coveringExpressionLengths')) {
coveringExpressionLengths = jsonDecoder.decodeList(
jsonPath + '.coveringExpressionLengths',
@@ -3287,11 +3236,13 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
+ var coveringExpressionOffsets = this.coveringExpressionOffsets;
if (coveringExpressionOffsets != null) {
result['coveringExpressionOffsets'] = coveringExpressionOffsets;
}
+ var coveringExpressionLengths = this.coveringExpressionLengths;
if (coveringExpressionLengths != null) {
result['coveringExpressionLengths'] = coveringExpressionLengths;
}
@@ -3339,16 +3290,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class ExtractLocalVariableOptions extends RefactoringOptions {
- String _name;
+ late String _name;
- bool _extractAll;
+ late bool _extractAll;
/// The name that the local variable should be given.
String get name => _name;
/// The name that the local variable should be given.
set name(String value) {
- assert(value != null);
_name = value;
}
@@ -3363,7 +3313,6 @@
/// variable. The expression used to initiate the refactoring will always be
/// replaced.
set extractAll(bool value) {
- assert(value != null);
_extractAll = value;
}
@@ -3373,7 +3322,7 @@
}
factory ExtractLocalVariableOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String name;
@@ -3403,8 +3352,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['name'] = name;
result['extractAll'] = extractAll;
return result;
@@ -3445,21 +3394,21 @@
///
/// Clients may not extend, implement or mix-in this class.
class ExtractMethodFeedback extends RefactoringFeedback {
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- String _returnType;
+ late String _returnType;
- List<String> _names;
+ late List<String> _names;
- bool _canCreateGetter;
+ late bool _canCreateGetter;
- List<RefactoringMethodParameter> _parameters;
+ late List<RefactoringMethodParameter> _parameters;
- List<int> _offsets;
+ late List<int> _offsets;
- List<int> _lengths;
+ late List<int> _lengths;
/// The offset to the beginning of the expression or statements that will be
/// extracted.
@@ -3468,7 +3417,6 @@
/// The offset to the beginning of the expression or statements that will be
/// extracted.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -3477,7 +3425,6 @@
/// The length of the expression or statements that will be extracted.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -3488,7 +3435,6 @@
/// The proposed return type for the method. If the returned element does not
/// have a declared return type, this field will contain an empty string.
set returnType(String value) {
- assert(value != null);
_returnType = value;
}
@@ -3497,7 +3443,6 @@
/// The proposed names for the method.
set names(List<String> value) {
- assert(value != null);
_names = value;
}
@@ -3506,7 +3451,6 @@
/// True if a getter could be created rather than a method.
set canCreateGetter(bool value) {
- assert(value != null);
_canCreateGetter = value;
}
@@ -3515,7 +3459,6 @@
/// The proposed parameters for the method.
set parameters(List<RefactoringMethodParameter> value) {
- assert(value != null);
_parameters = value;
}
@@ -3526,7 +3469,6 @@
/// The offsets of the expressions or statements that would be replaced by an
/// invocation of the method.
set offsets(List<int> value) {
- assert(value != null);
_offsets = value;
}
@@ -3543,7 +3485,6 @@
/// that expression is offsets[i], then the length of that expression is
/// lengths[i].
set lengths(List<int> value) {
- assert(value != null);
_lengths = value;
}
@@ -3567,7 +3508,7 @@
}
factory ExtractMethodFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int offset;
@@ -3608,7 +3549,7 @@
parameters = jsonDecoder.decodeList(
jsonPath + '.parameters',
json['parameters'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringMethodParameter.fromJson(
jsonDecoder, jsonPath, json));
} else {
@@ -3636,8 +3577,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['offset'] = offset;
result['length'] = length;
result['returnType'] = returnType;
@@ -3700,22 +3641,21 @@
///
/// Clients may not extend, implement or mix-in this class.
class ExtractMethodOptions extends RefactoringOptions {
- String _returnType;
+ late String _returnType;
- bool _createGetter;
+ late bool _createGetter;
- String _name;
+ late String _name;
- List<RefactoringMethodParameter> _parameters;
+ late List<RefactoringMethodParameter> _parameters;
- bool _extractAll;
+ late bool _extractAll;
/// The return type that should be defined for the method.
String get returnType => _returnType;
/// The return type that should be defined for the method.
set returnType(String value) {
- assert(value != null);
_returnType = value;
}
@@ -3726,7 +3666,6 @@
/// True if a getter should be created rather than a method. It is an error
/// if this field is true and the list of parameters is non-empty.
set createGetter(bool value) {
- assert(value != null);
_createGetter = value;
}
@@ -3735,7 +3674,6 @@
/// The name that the method should be given.
set name(String value) {
- assert(value != null);
_name = value;
}
@@ -3762,7 +3700,6 @@
/// - To add new parameters, omit their identifier.
/// - To remove some parameters, omit them in this list.
set parameters(List<RefactoringMethodParameter> value) {
- assert(value != null);
_parameters = value;
}
@@ -3775,7 +3712,6 @@
/// replaced by an invocation of the method. The expression or statements
/// used to initiate the refactoring will always be replaced.
set extractAll(bool value) {
- assert(value != null);
_extractAll = value;
}
@@ -3789,7 +3725,7 @@
}
factory ExtractMethodOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String returnType;
@@ -3817,7 +3753,7 @@
parameters = jsonDecoder.decodeList(
jsonPath + '.parameters',
json['parameters'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
RefactoringMethodParameter.fromJson(
jsonDecoder, jsonPath, json));
} else {
@@ -3844,8 +3780,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['returnType'] = returnType;
result['createGetter'] = createGetter;
result['name'] = name;
@@ -3896,16 +3832,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class InlineLocalVariableFeedback extends RefactoringFeedback {
- String _name;
+ late String _name;
- int _occurrences;
+ late int _occurrences;
/// The name of the variable being inlined.
String get name => _name;
/// The name of the variable being inlined.
set name(String value) {
- assert(value != null);
_name = value;
}
@@ -3914,7 +3849,6 @@
/// The number of times the variable occurs.
set occurrences(int value) {
- assert(value != null);
_occurrences = value;
}
@@ -3924,7 +3858,7 @@
}
factory InlineLocalVariableFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String name;
@@ -3948,8 +3882,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['name'] = name;
result['occurrences'] = occurrences;
return result;
@@ -4004,19 +3938,19 @@
///
/// Clients may not extend, implement or mix-in this class.
class InlineMethodFeedback extends RefactoringFeedback {
- String _className;
+ String? _className;
- String _methodName;
+ late String _methodName;
- bool _isDeclaration;
+ late bool _isDeclaration;
/// The name of the class enclosing the method being inlined. If not a class
/// member is being inlined, this field will be absent.
- String get className => _className;
+ String? get className => _className;
/// The name of the class enclosing the method being inlined. If not a class
/// member is being inlined, this field will be absent.
- set className(String value) {
+ set className(String? value) {
_className = value;
}
@@ -4025,7 +3959,6 @@
/// The name of the method (or function) being inlined.
set methodName(String value) {
- assert(value != null);
_methodName = value;
}
@@ -4036,22 +3969,21 @@
/// True if the declaration of the method is selected and all references
/// should be inlined.
set isDeclaration(bool value) {
- assert(value != null);
_isDeclaration = value;
}
InlineMethodFeedback(String methodName, bool isDeclaration,
- {String className}) {
+ {String? className}) {
this.className = className;
this.methodName = methodName;
this.isDeclaration = isDeclaration;
}
factory InlineMethodFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
- String className;
+ String? className;
if (json.containsKey('className')) {
className = jsonDecoder.decodeString(
jsonPath + '.className', json['className']);
@@ -4078,8 +4010,9 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
+ var className = this.className;
if (className != null) {
result['className'] = className;
}
@@ -4120,9 +4053,9 @@
///
/// Clients may not extend, implement or mix-in this class.
class InlineMethodOptions extends RefactoringOptions {
- bool _deleteSource;
+ late bool _deleteSource;
- bool _inlineAll;
+ late bool _inlineAll;
/// True if the method being inlined should be removed. It is an error if
/// this field is true and inlineAll is false.
@@ -4131,7 +4064,6 @@
/// True if the method being inlined should be removed. It is an error if
/// this field is true and inlineAll is false.
set deleteSource(bool value) {
- assert(value != null);
_deleteSource = value;
}
@@ -4142,7 +4074,6 @@
/// True if all invocations of the method should be inlined, or false if only
/// the invocation site used to create this refactoring should be inlined.
set inlineAll(bool value) {
- assert(value != null);
_inlineAll = value;
}
@@ -4152,7 +4083,7 @@
}
factory InlineMethodOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
bool deleteSource;
@@ -4182,8 +4113,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['deleteSource'] = deleteSource;
result['inlineAll'] = inlineAll;
return result;
@@ -4217,7 +4148,7 @@
///
/// Clients may not extend, implement or mix-in this class.
class KytheGetKytheEntriesParams implements RequestParams {
- String _file;
+ late String _file;
/// The file containing the code for which the Kythe Entry objects are being
/// requested.
@@ -4226,7 +4157,6 @@
/// The file containing the code for which the Kythe Entry objects are being
/// requested.
set file(String value) {
- assert(value != null);
_file = value;
}
@@ -4235,7 +4165,7 @@
}
factory KytheGetKytheEntriesParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String file;
@@ -4257,8 +4187,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['file'] = file;
return result;
}
@@ -4296,16 +4226,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class KytheGetKytheEntriesResult implements ResponseResult {
- List<KytheEntry> _entries;
+ late List<KytheEntry> _entries;
- List<String> _files;
+ late List<String> _files;
/// The list of KytheEntry objects for the queried file.
List<KytheEntry> get entries => _entries;
/// The list of KytheEntry objects for the queried file.
set entries(List<KytheEntry> value) {
- assert(value != null);
_entries = value;
}
@@ -4320,7 +4249,6 @@
/// to a referenced file that does not exist or generated files not being
/// generated or passed before the call to "getKytheEntries".
set files(List<String> value) {
- assert(value != null);
_files = value;
}
@@ -4330,7 +4258,7 @@
}
factory KytheGetKytheEntriesResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
List<KytheEntry> entries;
@@ -4338,7 +4266,7 @@
entries = jsonDecoder.decodeList(
jsonPath + '.entries',
json['entries'],
- (String jsonPath, Object json) =>
+ (String jsonPath, Object? json) =>
KytheEntry.fromJson(jsonDecoder, jsonPath, json));
} else {
throw jsonDecoder.mismatch(jsonPath, 'entries');
@@ -4365,8 +4293,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['entries'] =
entries.map((KytheEntry value) => value.toJson()).toList();
result['files'] = files;
@@ -4426,14 +4354,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class MoveFileOptions extends RefactoringOptions {
- String _newFile;
+ late String _newFile;
/// The new file path to which the given file is being moved.
String get newFile => _newFile;
/// The new file path to which the given file is being moved.
set newFile(String value) {
- assert(value != null);
_newFile = value;
}
@@ -4442,7 +4369,7 @@
}
factory MoveFileOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String newFile;
@@ -4465,8 +4392,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['newFile'] = newFile;
return result;
}
@@ -4500,11 +4427,11 @@
///
/// Clients may not extend, implement or mix-in this class.
class PluginErrorParams implements HasToJson {
- bool _isFatal;
+ late bool _isFatal;
- String _message;
+ late String _message;
- String _stackTrace;
+ late String _stackTrace;
/// A flag indicating whether the error is a fatal error, meaning that the
/// plugin will shutdown automatically after sending this notification. If
@@ -4517,7 +4444,6 @@
/// true, the server will not expect any other responses or notifications
/// from the plugin.
set isFatal(bool value) {
- assert(value != null);
_isFatal = value;
}
@@ -4526,7 +4452,6 @@
/// The error message indicating what kind of error was encountered.
set message(String value) {
- assert(value != null);
_message = value;
}
@@ -4537,7 +4462,6 @@
/// The stack trace associated with the generation of the error, used for
/// debugging the plugin.
set stackTrace(String value) {
- assert(value != null);
_stackTrace = value;
}
@@ -4548,7 +4472,7 @@
}
factory PluginErrorParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
bool isFatal;
@@ -4584,8 +4508,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['isFatal'] = isFatal;
result['message'] = message;
result['stackTrace'] = stackTrace;
@@ -4624,7 +4548,7 @@
/// Clients may not extend, implement or mix-in this class.
class PluginShutdownParams implements RequestParams {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Request toRequest(String id) {
@@ -4650,7 +4574,7 @@
/// Clients may not extend, implement or mix-in this class.
class PluginShutdownResult implements ResponseResult {
@override
- Map<String, dynamic> toJson() => <String, dynamic>{};
+ Map<String, Object> toJson() => <String, Object>{};
@override
Response toResponse(String id, int requestTime) {
@@ -4681,11 +4605,11 @@
///
/// Clients may not extend, implement or mix-in this class.
class PluginVersionCheckParams implements RequestParams {
- String _byteStorePath;
+ late String _byteStorePath;
- String _sdkPath;
+ late String _sdkPath;
- String _version;
+ late String _version;
/// The path to the directory containing the on-disk byte store that is to be
/// used by any analysis drivers that are created.
@@ -4694,7 +4618,6 @@
/// The path to the directory containing the on-disk byte store that is to be
/// used by any analysis drivers that are created.
set byteStorePath(String value) {
- assert(value != null);
_byteStorePath = value;
}
@@ -4705,7 +4628,6 @@
/// The path to the directory containing the SDK that is to be used by any
/// analysis drivers that are created.
set sdkPath(String value) {
- assert(value != null);
_sdkPath = value;
}
@@ -4716,7 +4638,6 @@
/// The version number of the plugin spec supported by the analysis server
/// that is executing the plugin.
set version(String value) {
- assert(value != null);
_version = value;
}
@@ -4728,7 +4649,7 @@
}
factory PluginVersionCheckParams.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String byteStorePath;
@@ -4764,8 +4685,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['byteStorePath'] = byteStorePath;
result['sdkPath'] = sdkPath;
result['version'] = version;
@@ -4812,15 +4733,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class PluginVersionCheckResult implements ResponseResult {
- bool _isCompatible;
+ late bool _isCompatible;
- String _name;
+ late String _name;
- String _version;
+ late String _version;
- String _contactInfo;
+ String? _contactInfo;
- List<String> _interestingFiles;
+ late List<String> _interestingFiles;
/// A flag indicating whether the plugin supports the same version of the
/// plugin spec as the analysis server. If the value is false, then the
@@ -4831,7 +4752,6 @@
/// plugin spec as the analysis server. If the value is false, then the
/// plugin is expected to shutdown after returning the response.
set isCompatible(bool value) {
- assert(value != null);
_isCompatible = value;
}
@@ -4842,7 +4762,6 @@
/// The name of the plugin. This value is only used when the server needs to
/// identify the plugin, either to the user or for debugging purposes.
set name(String value) {
- assert(value != null);
_name = value;
}
@@ -4853,17 +4772,16 @@
/// The version of the plugin. This value is only used when the server needs
/// to identify the plugin, either to the user or for debugging purposes.
set version(String value) {
- assert(value != null);
_version = value;
}
/// Information that the user can use to use to contact the maintainers of
/// the plugin when there is a problem.
- String get contactInfo => _contactInfo;
+ String? get contactInfo => _contactInfo;
/// Information that the user can use to use to contact the maintainers of
/// the plugin when there is a problem.
- set contactInfo(String value) {
+ set contactInfo(String? value) {
_contactInfo = value;
}
@@ -4878,13 +4796,12 @@
/// Otherwise, it will be used to identify the files for which the plugin
/// should be notified of changes.
set interestingFiles(List<String> value) {
- assert(value != null);
_interestingFiles = value;
}
PluginVersionCheckResult(bool isCompatible, String name, String version,
List<String> interestingFiles,
- {String contactInfo}) {
+ {String? contactInfo}) {
this.isCompatible = isCompatible;
this.name = name;
this.version = version;
@@ -4893,7 +4810,7 @@
}
factory PluginVersionCheckResult.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
bool isCompatible;
@@ -4916,7 +4833,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'version');
}
- String contactInfo;
+ String? contactInfo;
if (json.containsKey('contactInfo')) {
contactInfo = jsonDecoder.decodeString(
jsonPath + '.contactInfo', json['contactInfo']);
@@ -4946,11 +4863,12 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['isCompatible'] = isCompatible;
result['name'] = name;
result['version'] = version;
+ var contactInfo = this.contactInfo;
if (contactInfo != null) {
result['contactInfo'] = contactInfo;
}
@@ -5000,9 +4918,9 @@
///
/// Clients may not extend, implement or mix-in this class.
class PrioritizedSourceChange implements HasToJson {
- int _priority;
+ late int _priority;
- SourceChange _change;
+ late SourceChange _change;
/// The priority of the change. The value is expected to be non-negative, and
/// zero (0) is the lowest priority.
@@ -5011,7 +4929,6 @@
/// The priority of the change. The value is expected to be non-negative, and
/// zero (0) is the lowest priority.
set priority(int value) {
- assert(value != null);
_priority = value;
}
@@ -5020,7 +4937,6 @@
/// The change with which the relevance is associated.
set change(SourceChange value) {
- assert(value != null);
_change = value;
}
@@ -5030,7 +4946,7 @@
}
factory PrioritizedSourceChange.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int priority;
@@ -5054,8 +4970,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['priority'] = priority;
result['change'] = change.toJson();
return result;
@@ -5090,15 +5006,15 @@
class RefactoringFeedback implements HasToJson {
RefactoringFeedback();
- factory RefactoringFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json, Map responseJson) {
+ factory RefactoringFeedback.fromJson(JsonDecoder jsonDecoder, String jsonPath,
+ Object? json, Map responseJson) {
return refactoringFeedbackFromJson(
jsonDecoder, jsonPath, json, responseJson);
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
return result;
}
@@ -5130,13 +5046,13 @@
RefactoringOptions();
factory RefactoringOptions.fromJson(JsonDecoder jsonDecoder, String jsonPath,
- Object json, RefactoringKind kind) {
+ Object? json, RefactoringKind kind) {
return refactoringOptionsFromJson(jsonDecoder, jsonPath, json, kind);
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
return result;
}
@@ -5169,20 +5085,19 @@
///
/// Clients may not extend, implement or mix-in this class.
class RenameFeedback extends RefactoringFeedback {
- int _offset;
+ late int _offset;
- int _length;
+ late int _length;
- String _elementKindName;
+ late String _elementKindName;
- String _oldName;
+ late String _oldName;
/// The offset to the beginning of the name selected to be renamed.
int get offset => _offset;
/// The offset to the beginning of the name selected to be renamed.
set offset(int value) {
- assert(value != null);
_offset = value;
}
@@ -5191,7 +5106,6 @@
/// The length of the name selected to be renamed.
set length(int value) {
- assert(value != null);
_length = value;
}
@@ -5202,7 +5116,6 @@
/// The human-readable description of the kind of element being renamed (such
/// as “class” or “function type alias”).
set elementKindName(String value) {
- assert(value != null);
_elementKindName = value;
}
@@ -5211,7 +5124,6 @@
/// The old name of the element before the refactoring.
set oldName(String value) {
- assert(value != null);
_oldName = value;
}
@@ -5224,7 +5136,7 @@
}
factory RenameFeedback.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
int offset;
@@ -5260,8 +5172,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['offset'] = offset;
result['length'] = length;
result['elementKindName'] = elementKindName;
@@ -5302,14 +5214,13 @@
///
/// Clients may not extend, implement or mix-in this class.
class RenameOptions extends RefactoringOptions {
- String _newName;
+ late String _newName;
/// The name that the element should have after the refactoring.
String get newName => _newName;
/// The name that the element should have after the refactoring.
set newName(String value) {
- assert(value != null);
_newName = value;
}
@@ -5318,7 +5229,7 @@
}
factory RenameOptions.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
String newName;
@@ -5341,8 +5252,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['newName'] = newName;
return result;
}
@@ -5376,18 +5287,17 @@
///
/// Clients may not extend, implement or mix-in this class.
class RequestError implements HasToJson {
- RequestErrorCode _code;
+ late RequestErrorCode _code;
- String _message;
+ late String _message;
- String _stackTrace;
+ String? _stackTrace;
/// A code that uniquely identifies the error that occurred.
RequestErrorCode get code => _code;
/// A code that uniquely identifies the error that occurred.
set code(RequestErrorCode value) {
- assert(value != null);
_code = value;
}
@@ -5396,28 +5306,27 @@
/// A short description of the error.
set message(String value) {
- assert(value != null);
_message = value;
}
/// The stack trace associated with processing the request, used for
/// debugging the plugin.
- String get stackTrace => _stackTrace;
+ String? get stackTrace => _stackTrace;
/// The stack trace associated with processing the request, used for
/// debugging the plugin.
- set stackTrace(String value) {
+ set stackTrace(String? value) {
_stackTrace = value;
}
- RequestError(RequestErrorCode code, String message, {String stackTrace}) {
+ RequestError(RequestErrorCode code, String message, {String? stackTrace}) {
this.code = code;
this.message = message;
this.stackTrace = stackTrace;
}
factory RequestError.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
RequestErrorCode code;
@@ -5434,7 +5343,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, 'message');
}
- String stackTrace;
+ String? stackTrace;
if (json.containsKey('stackTrace')) {
stackTrace = jsonDecoder.decodeString(
jsonPath + '.stackTrace', json['stackTrace']);
@@ -5446,10 +5355,11 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['code'] = code.toJson();
result['message'] = message;
+ var stackTrace = this.stackTrace;
if (stackTrace != null) {
result['stackTrace'] = stackTrace;
}
@@ -5543,7 +5453,7 @@
}
factory RequestErrorCode.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return RequestErrorCode(json);
@@ -5569,16 +5479,15 @@
///
/// Clients may not extend, implement or mix-in this class.
class WatchEvent implements HasToJson {
- WatchEventType _type;
+ late WatchEventType _type;
- String _path;
+ late String _path;
/// The type of change represented by this event.
WatchEventType get type => _type;
/// The type of change represented by this event.
set type(WatchEventType value) {
- assert(value != null);
_type = value;
}
@@ -5587,7 +5496,6 @@
/// The absolute path of the file or directory that changed.
set path(String value) {
- assert(value != null);
_path = value;
}
@@ -5597,7 +5505,7 @@
}
factory WatchEvent.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
json ??= {};
if (json is Map) {
WatchEventType type;
@@ -5620,8 +5528,8 @@
}
@override
- Map<String, dynamic> toJson() {
- var result = <String, dynamic>{};
+ Map<String, Object> toJson() {
+ var result = <String, Object>{};
result['type'] = type.toJson();
result['path'] = path;
return result;
@@ -5691,7 +5599,7 @@
}
factory WatchEventType.fromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json) {
if (json is String) {
try {
return WatchEventType(json);
diff --git a/pkg/analyzer_plugin/lib/src/channel/isolate_channel.dart b/pkg/analyzer_plugin/lib/src/channel/isolate_channel.dart
index 2b35cc7..279e58f 100644
--- a/pkg/analyzer_plugin/lib/src/channel/isolate_channel.dart
+++ b/pkg/analyzer_plugin/lib/src/channel/isolate_channel.dart
@@ -31,7 +31,7 @@
@override
Future<Isolate> _spawnIsolate() {
return Isolate.spawn(
- (message) => entryPoint(message as SendPort), _receivePort.sendPort,
+ (message) => entryPoint(message as SendPort), _receivePort?.sendPort,
onError: _errorPort?.sendPort, onExit: _exitPort?.sendPort);
}
}
@@ -57,7 +57,7 @@
@override
Future<Isolate> _spawnIsolate() {
- return Isolate.spawnUri(pluginUri, <String>[], _receivePort.sendPort,
+ return Isolate.spawnUri(pluginUri, <String>[], _receivePort?.sendPort,
onError: _errorPort?.sendPort,
onExit: _exitPort?.sendPort,
packageConfig: packagesUri);
@@ -72,10 +72,10 @@
final SendPort _sendPort;
/// The port used to receive requests from the server.
- ReceivePort _receivePort;
+ late final ReceivePort _receivePort;
/// The subscription that needs to be cancelled when the channel is closed.
- StreamSubscription _subscription;
+ StreamSubscription? _subscription;
/// Initialize a newly created channel to communicate with the server.
PluginIsolateChannel(this._sendPort) {
@@ -85,21 +85,17 @@
@override
void close() {
- if (_subscription != null) {
- _subscription.cancel();
- _subscription = null;
- }
+ _subscription?.cancel();
+ _subscription = null;
}
@override
void listen(void Function(Request request) onRequest,
- {Function onError, void Function() onDone}) {
+ {Function? onError, void Function()? onDone}) {
void onData(data) {
var requestMap = data as Map<String, Object>;
var request = Request.fromJson(requestMap);
- if (request != null) {
- onRequest(request);
- }
+ onRequest(request);
}
if (_subscription != null) {
@@ -130,20 +126,20 @@
/// The isolate in which the plugin is running, or `null` if the plugin has
/// not yet been started by invoking [listen].
- Isolate _isolate;
+ Isolate? _isolate;
/// The port used to send requests to the plugin, or `null` if the plugin has
/// not yet been started by invoking [listen].
- SendPort _sendPort;
+ SendPort? _sendPort;
/// The port used to receive responses and notifications from the plugin.
- ReceivePort _receivePort;
+ ReceivePort? _receivePort;
/// The port used to receive unhandled exceptions thrown in the plugin.
- ReceivePort _errorPort;
+ ReceivePort? _errorPort;
/// The port used to receive notification when the plugin isolate has exited.
- ReceivePort _exitPort;
+ ReceivePort? _exitPort;
/// Return a communication channel appropriate for communicating with a
/// built-in plugin.
@@ -180,23 +176,30 @@
@override
Future<void> listen(void Function(Response response) onResponse,
void Function(Notification notification) onNotification,
- {void Function(dynamic error) onError, void Function() onDone}) async {
+ {void Function(dynamic error)? onError, void Function()? onDone}) async {
if (_isolate != null) {
throw StateError('Cannot listen to the same channel more than once.');
}
- _receivePort = ReceivePort();
+
+ var receivePort = ReceivePort();
+ _receivePort = receivePort;
+
if (onError != null) {
- _errorPort = ReceivePort();
- _errorPort.listen((error) {
+ var errorPort = ReceivePort();
+ _errorPort = errorPort;
+ errorPort.listen((error) {
onError(error);
});
}
+
if (onDone != null) {
- _exitPort = ReceivePort();
- _exitPort.listen((_) {
+ var exitPort = ReceivePort();
+ _exitPort = exitPort;
+ exitPort.listen((_) {
onDone();
});
}
+
try {
_isolate = await _spawnIsolate();
} catch (exception, stackTrace) {
@@ -214,8 +217,9 @@
close();
return null;
}
+
var channelReady = Completer<void>();
- _receivePort.listen((dynamic input) {
+ receivePort.listen((dynamic input) {
if (input is SendPort) {
_sendPort = input;
channelReady.complete(null);
@@ -231,16 +235,18 @@
}
}
});
+
return channelReady.future;
}
@override
void sendRequest(Request request) {
- if (_sendPort != null) {
+ var sendPort = _sendPort;
+ if (sendPort != null) {
var jsonData = request.toJson();
var encodedRequest = json.encode(jsonData);
instrumentationService.logPluginRequest(pluginId, encodedRequest);
- _sendPort.send(jsonData);
+ sendPort.send(jsonData);
}
}
diff --git a/pkg/analyzer_plugin/lib/src/protocol/protocol_internal.dart b/pkg/analyzer_plugin/lib/src/protocol/protocol_internal.dart
index 5615b1b..bc7322c 100644
--- a/pkg/analyzer_plugin/lib/src/protocol/protocol_internal.dart
+++ b/pkg/analyzer_plugin/lib/src/protocol/protocol_internal.dart
@@ -93,7 +93,7 @@
}
/// Returns the [FileEdit] for the given [file], maybe `null`.
-SourceFileEdit getChangeFileEdit(SourceChange change, String file) {
+SourceFileEdit? getChangeFileEdit(SourceChange change, String file) {
for (var fileEdit in change.edits) {
if (fileEdit.file == file) {
return fileEdit;
@@ -105,7 +105,7 @@
/// Compare the lists [listA] and [listB], using [itemEqual] to compare
/// list elements.
bool listEqual<T>(
- List<T> listA, List<T> listB, bool Function(T a, T b) itemEqual) {
+ List<T>? listA, List<T>? listB, bool Function(T a, T b) itemEqual) {
if (listA == null) {
return listB == null;
}
@@ -126,7 +126,7 @@
/// Compare the maps [mapA] and [mapB], using [valueEqual] to compare map
/// values.
bool mapEqual<K, V>(
- Map<K, V> mapA, Map<K, V> mapB, bool Function(V a, V b) valueEqual) {
+ Map<K, V>? mapA, Map<K, V>? mapB, bool Function(V a, V b) valueEqual) {
if (mapA == null) {
return mapB == null;
}
@@ -140,7 +140,7 @@
if (!mapB.containsKey(key)) {
return false;
}
- if (!valueEqual(mapA[key], mapB[key])) {
+ if (!valueEqual(mapA[key]!, mapB[key]!)) {
return false;
}
}
@@ -150,7 +150,7 @@
/// Translate the input [map], applying [keyCallback] to all its keys, and
/// [valueCallback] to all its values.
Map<KR, VR> mapMap<KP, VP, KR, VR>(Map<KP, VP> map,
- {KR Function(KP key) keyCallback, VR Function(VP value) valueCallback}) {
+ {KR Function(KP key)? keyCallback, VR Function(VP value)? valueCallback}) {
Map<KR, VR> result = HashMap<KR, VR>();
map.forEach((key, value) {
KR resultKey;
@@ -170,8 +170,8 @@
return result;
}
-RefactoringProblemSeverity maxRefactoringProblemSeverity(
- RefactoringProblemSeverity a, RefactoringProblemSeverity b) {
+RefactoringProblemSeverity? maxRefactoringProblemSeverity(
+ RefactoringProblemSeverity? a, RefactoringProblemSeverity? b) {
if (b == null) {
return a;
}
@@ -194,7 +194,7 @@
/// Create a [RefactoringFeedback] corresponding the given [kind].
RefactoringFeedback refactoringFeedbackFromJson(
- JsonDecoder jsonDecoder, String jsonPath, Object json, Map feedbackJson) {
+ JsonDecoder jsonDecoder, String jsonPath, Object? json, Map feedbackJson) {
var kind = jsonDecoder.refactoringKind;
if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
return ExtractLocalVariableFeedback.fromJson(jsonDecoder, jsonPath, json);
@@ -211,12 +211,12 @@
if (kind == RefactoringKind.RENAME) {
return RenameFeedback.fromJson(jsonDecoder, jsonPath, json);
}
- return null;
+ throw StateError('Unexpected refactoring kind');
}
/// Create a [RefactoringOptions] corresponding the given [kind].
RefactoringOptions refactoringOptionsFromJson(JsonDecoder jsonDecoder,
- String jsonPath, Object json, RefactoringKind kind) {
+ String jsonPath, Object? json, RefactoringKind kind) {
if (kind == RefactoringKind.EXTRACT_LOCAL_VARIABLE) {
return ExtractLocalVariableOptions.fromJson(jsonDecoder, jsonPath, json);
}
@@ -232,13 +232,14 @@
if (kind == RefactoringKind.RENAME) {
return RenameOptions.fromJson(jsonDecoder, jsonPath, json);
}
- return null;
+ throw StateError('Unexpected refactoring kind');
}
/// Type of callbacks used to decode parts of JSON objects. [jsonPath] is a
/// string describing the part of the JSON object being decoded, and [value] is
/// the part to decode.
-typedef JsonDecoderCallback<E> = E Function(String jsonPath, dynamic value);
+typedef JsonDecoderCallback<E extends Object> = E Function(
+ String jsonPath, dynamic value);
/// Instances of the class [HasToJson] implement [toJson] method that returns
/// a JSON presentation.
@@ -253,11 +254,11 @@
/// Retrieve the RefactoringKind that should be assumed when decoding
/// refactoring feedback objects, or null if no refactoring feedback object is
/// expected to be encountered.
- RefactoringKind get refactoringKind;
+ RefactoringKind? get refactoringKind;
/// Decode a JSON object that is expected to be a boolean. The strings "true"
/// and "false" are also accepted.
- bool decodeBool(String jsonPath, Object json) {
+ bool decodeBool(String jsonPath, Object? json) {
if (json is bool) {
return json;
} else if (json == 'true') {
@@ -287,7 +288,7 @@
/// Decode a JSON object that is expected to be an integer. A string
/// representation of an integer is also accepted.
- int decodeInt(String jsonPath, Object json) {
+ int decodeInt(String jsonPath, Object? json) {
if (json is int) {
return json;
} else if (json is String) {
@@ -304,11 +305,11 @@
/// to decode the items in the list.
///
/// The type parameter [E] is the expected type of the elements in the list.
- List<E> decodeList<E>(String jsonPath, Object json,
- [JsonDecoderCallback<E> decoder]) {
+ List<E> decodeList<E extends Object>(String jsonPath, Object? json,
+ [JsonDecoderCallback<E>? decoder]) {
if (json == null) {
return <E>[];
- } else if (json is List) {
+ } else if (json is List && decoder != null) {
var result = <E>[];
for (var i = 0; i < json.length; i++) {
result.add(decoder('$jsonPath[$i]', json[i]));
@@ -321,9 +322,10 @@
/// Decode a JSON object that is expected to be a Map. [keyDecoder] is used
/// to decode the keys, and [valueDecoder] is used to decode the values.
- Map<K, V> decodeMap<K, V>(String jsonPath, Object jsonData,
- {JsonDecoderCallback<K> keyDecoder,
- JsonDecoderCallback<V> valueDecoder}) {
+ Map<K, V> decodeMap<K extends Object, V extends Object>(
+ String jsonPath, Object? jsonData,
+ {JsonDecoderCallback<K>? keyDecoder,
+ JsonDecoderCallback<V>? valueDecoder}) {
if (jsonData == null) {
return {};
} else if (jsonData is Map) {
@@ -347,7 +349,7 @@
}
/// Decode a JSON object that is expected to be a string.
- String decodeString(String jsonPath, Object json) {
+ String decodeString(String jsonPath, Object? json) {
if (json is String) {
return json;
} else {
@@ -371,7 +373,11 @@
throw mismatch(
disambiguatorPath, 'One of: ${decoders.keys.toList()}', jsonData);
}
- return decoders[disambiguator](jsonPath, jsonData);
+ var decoder = decoders[disambiguator];
+ if (decoder == null) {
+ throw mismatch(disambiguatorPath, 'Non-null decoder', jsonData);
+ }
+ return decoder(jsonPath, jsonData);
} else {
throw mismatch(jsonPath, 'Map', jsonData);
}
@@ -379,11 +385,11 @@
/// Create an exception to throw if the JSON object at [jsonPath] fails to
/// match the API definition of [expected].
- dynamic mismatch(String jsonPath, String expected, [Object actual]);
+ Object mismatch(String jsonPath, String expected, [Object? actual]);
/// Create an exception to throw if the JSON object at [jsonPath] is missing
/// the key [key].
- dynamic missingKey(String jsonPath, String key);
+ Object missingKey(String jsonPath, String key);
}
/// JsonDecoder for decoding requests. Errors are reporting by throwing a
@@ -395,13 +401,13 @@
RequestDecoder(this.request);
@override
- RefactoringKind get refactoringKind {
+ RefactoringKind? get refactoringKind {
// Refactoring feedback objects should never appear in requests.
return null;
}
@override
- dynamic mismatch(String jsonPath, String expected, [Object actual]) {
+ Object mismatch(String jsonPath, String expected, [Object? actual]) {
var buffer = StringBuffer();
buffer.write('Expected to be ');
buffer.write(expected);
@@ -415,7 +421,7 @@
}
@override
- dynamic missingKey(String jsonPath, String key) {
+ Object missingKey(String jsonPath, String key) {
return RequestFailure(RequestErrorFactory.invalidParameter(
jsonPath, 'Expected to contain key ${json.encode(key)}'));
}
@@ -431,12 +437,12 @@
/// used only for testing. Errors are reported using bare [Exception] objects.
class ResponseDecoder extends JsonDecoder {
@override
- final RefactoringKind refactoringKind;
+ final RefactoringKind? refactoringKind;
ResponseDecoder(this.refactoringKind);
@override
- dynamic mismatch(String jsonPath, String expected, [Object actual]) {
+ Object mismatch(String jsonPath, String expected, [Object? actual]) {
var buffer = StringBuffer();
buffer.write('Expected ');
buffer.write(expected);
@@ -451,7 +457,7 @@
}
@override
- dynamic missingKey(String jsonPath, String key) {
+ Object missingKey(String jsonPath, String key) {
return Exception('Missing key $key at $jsonPath');
}
}
diff --git a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
index 58d3a20..eb1cded 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_core.dart
@@ -17,24 +17,23 @@
/// A builder used to build a [SourceChange].
class ChangeBuilderImpl implements ChangeBuilder {
- /// The workspace in which the change builder should operate, or `null` if no
- /// Dart files will be changed.
+ /// The workspace in which the change builder should operate.
final ChangeWorkspace workspace;
/// The end-of-line marker used in the file being edited, or `null` if the
/// default marker should be used.
- final String eol;
+ final String? eol;
/// A table mapping group ids to the associated linked edit groups.
final Map<String, LinkedEditGroup> _linkedEditGroups =
<String, LinkedEditGroup>{};
/// The source change selection or `null` if none.
- Position _selection;
+ Position? _selection;
/// The range of the selection for the change being built, or `null` if there
/// is no selection.
- SourceRange _selectionRange;
+ SourceRange? _selectionRange;
/// The set of [Position]s that belong to the current [EditBuilderImpl] and
/// should not be updated in result of inserting this builder.
@@ -50,12 +49,12 @@
/// create changes for Dart files, then either a [session] or a [workspace]
/// must be provided (but not both).
ChangeBuilderImpl(
- {AnalysisSession session, ChangeWorkspace workspace, this.eol})
+ {AnalysisSession? session, ChangeWorkspace? workspace, this.eol})
: assert(session == null || workspace == null),
- workspace = workspace ?? _SingleSessionWorkspace(session);
+ workspace = workspace ?? _SingleSessionWorkspace(session!);
@override
- SourceRange get selectionRange => _selectionRange;
+ SourceRange? get selectionRange => _selectionRange;
@override
SourceChange get sourceChange {
@@ -75,8 +74,9 @@
_linkedEditGroups.forEach((String name, LinkedEditGroup group) {
change.addLinkedEditGroup(group);
});
- if (_selection != null) {
- change.selection = _selection;
+ var selection = _selection;
+ if (selection != null) {
+ change.selection = selection;
}
return change;
}
@@ -84,14 +84,14 @@
@override
Future<void> addDartFileEdit(
String path, void Function(DartFileEditBuilder builder) buildFileEdit,
- {ImportPrefixGenerator importPrefixGenerator}) async {
+ {ImportPrefixGenerator? importPrefixGenerator}) async {
if (_genericFileEditBuilders.containsKey(path)) {
throw StateError("Can't create both a generic file edit and a dart file "
'edit for the same file');
}
var builder = _dartFileEditBuilders[path];
if (builder == null) {
- builder = await createDartFileEditBuilder(path);
+ builder = await _createDartFileEditBuilder(path);
if (builder != null) {
_dartFileEditBuilders[path] = builder;
}
@@ -102,13 +102,6 @@
}
}
- @Deprecated('Use either addDartFileEdit or addGenericFileEdit')
- @override
- Future<void> addFileEdit(
- String path, void Function(FileEditBuilder builder) buildFileEdit) async {
- return addGenericFileEdit(path, buildFileEdit);
- }
-
@override
Future<void> addGenericFileEdit(
String path, void Function(FileEditBuilder builder) buildFileEdit) async {
@@ -118,14 +111,10 @@
}
var builder = _genericFileEditBuilders[path];
if (builder == null) {
- builder = await createGenericFileEditBuilder(path);
- if (builder != null) {
- _genericFileEditBuilders[path] = builder;
- }
+ builder = FileEditBuilderImpl(this, path, 0);
+ _genericFileEditBuilders[path] = builder;
}
- if (builder != null) {
- buildFileEdit(builder);
- }
+ buildFileEdit(builder);
}
@override
@@ -134,7 +123,10 @@
for (var entry in _linkedEditGroups.entries) {
copy._linkedEditGroups[entry.key] = _copyLinkedEditGroup(entry.value);
}
- copy._selection = _copyPosition(_selection);
+ var selection = _selection;
+ if (selection != null) {
+ copy._selection = _copyPosition(selection);
+ }
copy._selectionRange = _selectionRange;
copy._lockedPositions.addAll(_lockedPositions);
for (var entry in _genericFileEditBuilders.entries) {
@@ -165,50 +157,6 @@
return copy;
}
- /// Create and return a [DartFileEditBuilder] that can be used to build edits
- /// to the Dart file with the given [path].
- Future<DartFileEditBuilderImpl> createDartFileEditBuilder(String path) async {
- // TODO(brianwilkerson) Make this method private when
- // `DartChangeBuilderImpl` is removed.
- if (workspace == null) {
- throw StateError("Can't create a DartFileEditBuilder without providing "
- 'either a session or a workspace');
- }
- if (!workspace.containsFile(path)) {
- return null;
- }
-
- var session = workspace.getSession(path);
- var result = await session.getResolvedUnit(path);
- var state = result?.state ?? ResultState.INVALID_FILE_TYPE;
- if (state == ResultState.INVALID_FILE_TYPE) {
- throw AnalysisException('Cannot analyze "$path"');
- }
- var timeStamp = state == ResultState.VALID ? 0 : -1;
-
- var declaredUnit = result.unit.declaredElement;
- var libraryUnit = declaredUnit.library.definingCompilationUnit;
-
- DartFileEditBuilderImpl libraryEditBuilder;
- if (libraryUnit != declaredUnit) {
- // If the receiver is a part file builder, then proactively cache the
- // library file builder so that imports can be finalized synchronously.
- await addDartFileEdit(libraryUnit.source.fullName, (builder) {
- libraryEditBuilder = builder as DartFileEditBuilderImpl;
- });
- }
-
- return DartFileEditBuilderImpl(this, result, timeStamp, libraryEditBuilder);
- }
-
- /// Create and return a [FileEditBuilder] that can be used to build edits to
- /// the file with the given [path].
- Future<FileEditBuilderImpl> createGenericFileEditBuilder(String path) async {
- // TODO(brianwilkerson) Make this method private when
- // `DartChangeBuilderImpl` is removed.
- return FileEditBuilderImpl(this, path, 0);
- }
-
/// Return the linked edit group with the given [groupName], creating it if it
/// did not already exist.
LinkedEditGroup getLinkedEditGroup(String groupName) {
@@ -233,7 +181,38 @@
/// Return a copy of the [position].
Position _copyPosition(Position position) {
- return position == null ? null : Position(position.file, position.offset);
+ return Position(position.file, position.offset);
+ }
+
+ /// Create and return a [DartFileEditBuilder] that can be used to build edits
+ /// to the Dart file with the given [path].
+ Future<DartFileEditBuilderImpl?> _createDartFileEditBuilder(
+ String? path) async {
+ if (path == null || !(workspace.containsFile(path) ?? false)) {
+ return null;
+ }
+
+ var session = workspace.getSession(path);
+ var result = await session?.getResolvedUnit(path);
+ var state = result?.state ?? ResultState.INVALID_FILE_TYPE;
+ if (state == ResultState.INVALID_FILE_TYPE) {
+ throw AnalysisException('Cannot analyze "$path"');
+ }
+ var timeStamp = state == ResultState.VALID ? 0 : -1;
+
+ var declaredUnit = result!.unit?.declaredElement;
+ var libraryUnit = declaredUnit?.library.definingCompilationUnit;
+
+ DartFileEditBuilderImpl? libraryEditBuilder;
+ if (libraryUnit != null && libraryUnit != declaredUnit) {
+ // If the receiver is a part file builder, then proactively cache the
+ // library file builder so that imports can be finalized synchronously.
+ await addDartFileEdit(libraryUnit.source.fullName, (builder) {
+ libraryEditBuilder = builder as DartFileEditBuilderImpl;
+ });
+ }
+
+ return DartFileEditBuilderImpl(this, result, timeStamp, libraryEditBuilder);
}
void _setSelectionRange(SourceRange range) {
@@ -255,8 +234,9 @@
_updatePosition(position);
}
}
- if (_selection != null) {
- _updatePosition(_selection);
+ var selection = _selection;
+ if (selection != null) {
+ _updatePosition(selection);
}
}
}
@@ -275,11 +255,11 @@
/// The range of the selection for the change being built, or `null` if the
/// selection is not inside the change being built.
- SourceRange _selectionRange;
+ SourceRange? _selectionRange;
/// The end-of-line marker used in the file being edited, or `null` if the
/// default marker should be used.
- String _eol;
+ String? _eol;
/// The buffer in which the content of the edit is being composed.
final StringBuffer _buffer = StringBuffer();
@@ -317,7 +297,7 @@
@override
void addSimpleLinkedEdit(String groupName, String text,
- {LinkedEditSuggestionKind kind, List<String> suggestions}) {
+ {LinkedEditSuggestionKind? kind, List<String>? suggestions}) {
addLinkedEdit(groupName, (LinkedEditBuilder builder) {
builder.write(text);
if (kind != null && suggestions != null) {
@@ -354,7 +334,7 @@
}
@override
- void writeln([String string]) {
+ void writeln([String? string]) {
if (string != null) {
_buffer.write(string);
}
@@ -561,7 +541,7 @@
}
@override
- void writeln([String string]) {
+ void writeln([String? string]) {
editBuilder.writeln(string);
}
}
@@ -573,14 +553,14 @@
_SingleSessionWorkspace(this.session);
@override
- bool containsFile(String path) {
+ bool? containsFile(String path) {
var analysisContext = session.analysisContext;
return analysisContext.contextRoot.isAnalyzed(path);
}
@override
- AnalysisSession getSession(String path) {
- if (containsFile(path)) {
+ AnalysisSession? getSession(String path) {
+ if (containsFile(path) ?? false) {
return session;
}
throw StateError('Not in a context root: $path');
diff --git a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
index 6f0ab75..443c711 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/change_builder/change_builder_dart.dart
@@ -4,7 +4,6 @@
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/analysis/results.dart';
-import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
@@ -21,38 +20,8 @@
import 'package:analyzer_plugin/src/utilities/string_utilities.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
-import 'package:analyzer_plugin/utilities/change_builder/change_workspace.dart';
import 'package:analyzer_plugin/utilities/range_factory.dart';
import 'package:dart_style/dart_style.dart';
-import 'package:meta/meta.dart';
-
-/// A [ChangeBuilder] used to build changes in Dart files.
-@Deprecated('Use ChangeBuilder')
-class DartChangeBuilderImpl extends ChangeBuilderImpl
- implements DartChangeBuilder {
- /// Initialize a newly created change builder.
- @Deprecated('Use ChangeBuilder(session: session)')
- DartChangeBuilderImpl(AnalysisSession session) : super(session: session);
-
- @Deprecated('Use ChangeBuilder(workspace: workspace)')
- DartChangeBuilderImpl.forWorkspace(ChangeWorkspace workspace)
- : super(workspace: workspace);
-
- @Deprecated('Use ChangeBuilder.addDartFileEdit')
- @override
- Future<void> addFileEdit(
- String path, void Function(DartFileEditBuilder builder) buildFileEdit,
- {ImportPrefixGenerator importPrefixGenerator}) {
- return super.addDartFileEdit(path, buildFileEdit,
- importPrefixGenerator: importPrefixGenerator);
- }
-
- @override
- Future<DartFileEditBuilderImpl> createGenericFileEditBuilder(
- String path) async {
- return super.createDartFileEditBuilder(path);
- }
-}
/// An [EditBuilder] used to build edits in Dart files.
class DartEditBuilderImpl extends EditBuilderImpl implements DartEditBuilder {
@@ -64,14 +33,14 @@
/// The enclosing class element, possibly `null`.
/// This field is lazily initialized in [_initializeEnclosingElements].
- ClassElement _enclosingClass;
+ ClassElement? _enclosingClass;
/// The enclosing executable element, possibly `null`.
/// This field is lazily initialized in [_initializeEnclosingElements].
- ExecutableElement _enclosingExecutable;
+ ExecutableElement? _enclosingExecutable;
/// If not `null`, [write] will copy everything into this buffer.
- StringBuffer _carbonCopyBuffer;
+ StringBuffer? _carbonCopyBuffer;
/// Initialize a newly created builder to build a source edit.
DartEditBuilderImpl(
@@ -103,13 +72,13 @@
@override
void writeClassDeclaration(String name,
- {Iterable<DartType> interfaces,
+ {Iterable<DartType>? interfaces,
bool isAbstract = false,
- void Function() membersWriter,
- Iterable<DartType> mixins,
- String nameGroupName,
- DartType superclass,
- String superclassGroupName}) {
+ void Function()? membersWriter,
+ Iterable<DartType>? mixins,
+ String? nameGroupName,
+ DartType? superclass,
+ String? superclassGroupName}) {
// TODO(brianwilkerson) Add support for type parameters, probably as a
// parameterWriter parameter.
if (isAbstract) {
@@ -141,15 +110,15 @@
@override
void writeConstructorDeclaration(String className,
- {ArgumentList argumentList,
- void Function() bodyWriter,
- String classNameGroupName,
- SimpleIdentifier constructorName,
- String constructorNameGroupName,
- List<String> fieldNames,
- void Function() initializerWriter,
+ {ArgumentList? argumentList,
+ void Function()? bodyWriter,
+ String? classNameGroupName,
+ SimpleIdentifier? constructorName,
+ String? constructorNameGroupName,
+ List<String>? fieldNames,
+ void Function()? initializerWriter,
bool isConst = false,
- void Function() parameterWriter}) {
+ void Function()? parameterWriter}) {
if (isConst) {
write(Keyword.CONST.lexeme);
write(' ');
@@ -197,13 +166,13 @@
@override
void writeFieldDeclaration(String name,
- {void Function() initializerWriter,
+ {void Function()? initializerWriter,
bool isConst = false,
bool isFinal = false,
bool isStatic = false,
- String nameGroupName,
- DartType type,
- String typeGroupName}) {
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName}) {
if (isStatic) {
write(Keyword.STATIC.lexeme);
write(' ');
@@ -239,12 +208,12 @@
@override
void writeFunctionDeclaration(String name,
- {void Function() bodyWriter,
+ {void Function()? bodyWriter,
bool isStatic = false,
- String nameGroupName,
- void Function() parameterWriter,
- DartType returnType,
- String returnTypeGroupName}) {
+ String? nameGroupName,
+ void Function()? parameterWriter,
+ DartType? returnType,
+ String? returnTypeGroupName}) {
if (isStatic) {
write(Keyword.STATIC.lexeme);
write(' ');
@@ -278,11 +247,11 @@
@override
void writeGetterDeclaration(String name,
- {void Function() bodyWriter,
+ {void Function()? bodyWriter,
bool isStatic = false,
- String nameGroupName,
- DartType returnType,
- String returnTypeGroupName}) {
+ String? nameGroupName,
+ DartType? returnType,
+ String? returnTypeGroupName}) {
if (isStatic) {
write(Keyword.STATIC.lexeme);
write(' ');
@@ -317,13 +286,15 @@
var import = _getBestImportForName(imports, name);
if (import == null) {
var library = dartFileEditBuilder._importLibrary(uris[0]);
- if (library.prefix != null) {
- write(library.prefix);
+ var prefix = library.prefix;
+ if (prefix != null) {
+ write(prefix);
write('.');
}
} else {
- if (import.prefix != null) {
- write(import.prefix.displayName);
+ var prefix = import.prefix;
+ if (prefix != null) {
+ write(prefix.displayName);
write('.');
}
}
@@ -332,12 +303,12 @@
@override
void writeLocalVariableDeclaration(String name,
- {void Function() initializerWriter,
+ {void Function()? initializerWriter,
bool isConst = false,
bool isFinal = false,
- String nameGroupName,
- DartType type,
- String typeGroupName}) {
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName}) {
var typeRequired = true;
if (isConst) {
write(Keyword.CONST.lexeme);
@@ -370,10 +341,10 @@
@override
void writeMixinDeclaration(String name,
- {Iterable<DartType> interfaces,
- void Function() membersWriter,
- String nameGroupName,
- Iterable<DartType> superclassConstraints}) {
+ {Iterable<DartType>? interfaces,
+ void Function()? membersWriter,
+ String? nameGroupName,
+ Iterable<DartType>? superclassConstraints}) {
// TODO(brianwilkerson) Add support for type parameters, probably as a
// parameterWriter parameter.
write('mixin ');
@@ -394,8 +365,8 @@
@override
void writeOverride(
ExecutableElement element, {
- StringBuffer displayTextBuffer,
- String returnTypeGroupName,
+ StringBuffer? displayTextBuffer,
+ String? returnTypeGroupName,
bool invokeSuper = false,
}) {
void withCarbonCopyBuffer(Function() f) {
@@ -536,13 +507,13 @@
void writeParameter(String name,
{bool isCovariant = false,
bool isRequiredNamed = false,
- ExecutableElement methodBeingCopied,
- String nameGroupName,
- DartType type,
- String typeGroupName}) {
+ ExecutableElement? methodBeingCopied,
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName}) {
bool writeType() {
if (typeGroupName != null) {
- bool hasType;
+ late bool hasType;
addLinkedEdit(typeGroupName, (DartLinkedEditBuilder builder) {
hasType = _writeType(type, methodBeingCopied: methodBeingCopied);
builder.addSuperTypesAsSuggestions(type);
@@ -619,7 +590,7 @@
@override
void writeParameters(Iterable<ParameterElement> parameters,
- {ExecutableElement methodBeingCopied}) {
+ {ExecutableElement? methodBeingCopied}) {
var parameterNames = <String>{};
for (var i = 0; i < parameters.length; i++) {
var name = parameters.elementAt(i).name;
@@ -713,11 +684,11 @@
@override
void writeSetterDeclaration(String name,
- {void Function() bodyWriter,
+ {void Function()? bodyWriter,
bool isStatic = false,
- String nameGroupName,
- DartType parameterType,
- String parameterTypeGroupName}) {
+ String? nameGroupName,
+ DartType? parameterType,
+ String? parameterTypeGroupName}) {
if (isStatic) {
write(Keyword.STATIC.lexeme);
write(' ');
@@ -747,10 +718,10 @@
}
@override
- bool writeType(DartType type,
+ bool writeType(DartType? type,
{bool addSupertypeProposals = false,
- String groupName,
- ExecutableElement methodBeingCopied,
+ String? groupName,
+ ExecutableElement? methodBeingCopied,
bool required = false}) {
var wroteType = false;
if (type != null && !type.isDynamic) {
@@ -774,7 +745,7 @@
@override
void writeTypeParameter(TypeParameterElement typeParameter,
- {ExecutableElement methodBeingCopied}) {
+ {ExecutableElement? methodBeingCopied}) {
write(typeParameter.name);
if (typeParameter.bound != null) {
write(' extends ');
@@ -784,7 +755,7 @@
@override
void writeTypeParameters(List<TypeParameterElement> typeParameters,
- {ExecutableElement methodBeingCopied}) {
+ {ExecutableElement? methodBeingCopied}) {
if (typeParameters.isNotEmpty) {
write('<');
var isFirst = true;
@@ -800,7 +771,7 @@
}
@override
- void writeTypes(Iterable<DartType> types, {String prefix}) {
+ void writeTypes(Iterable<DartType>? types, {String? prefix}) {
if (types == null || types.isEmpty) {
return;
}
@@ -854,7 +825,7 @@
}
void _addSuperTypeProposals(
- LinkedEditBuilder builder, DartType type, Set<DartType> alreadyAdded) {
+ LinkedEditBuilder builder, DartType? type, Set<DartType> alreadyAdded) {
if (type is InterfaceType && alreadyAdded.add(type)) {
builder.addSuggestion(
LinkedEditSuggestionKind.TYPE,
@@ -879,7 +850,7 @@
return name;
}
- String _getBaseNameFromExpression(Expression expression) {
+ String? _getBaseNameFromExpression(Expression expression) {
if (expression is AsExpression) {
return _getBaseNameFromExpression(expression.expression);
} else if (expression is ParenthesizedExpression) {
@@ -888,7 +859,7 @@
return _getBaseNameFromUnwrappedExpression(expression);
}
- String _getBaseNameFromLocationInParent(Expression expression) {
+ String? _getBaseNameFromLocationInParent(Expression expression) {
// value in named expression
if (expression.parent is NamedExpression) {
var namedExpression = expression.parent as NamedExpression;
@@ -906,8 +877,8 @@
return null;
}
- String _getBaseNameFromUnwrappedExpression(Expression expression) {
- String name;
+ String? _getBaseNameFromUnwrappedExpression(Expression expression) {
+ String? name;
// analyze expressions
if (expression is SimpleIdentifier) {
return expression.name;
@@ -920,22 +891,20 @@
} else if (expression is InstanceCreationExpression) {
var constructorName = expression.constructorName;
var typeName = constructorName.type;
- if (typeName != null) {
- var typeNameIdentifier = typeName.name;
- // new ClassName()
- if (typeNameIdentifier is SimpleIdentifier) {
- return typeNameIdentifier.name;
+ var typeNameIdentifier = typeName.name;
+ // new ClassName()
+ if (typeNameIdentifier is SimpleIdentifier) {
+ return typeNameIdentifier.name;
+ }
+ // new prefix.name();
+ if (typeNameIdentifier is PrefixedIdentifier) {
+ var prefixed = typeNameIdentifier;
+ // new prefix.ClassName()
+ if (prefixed.prefix.staticElement is PrefixElement) {
+ return prefixed.identifier.name;
}
- // new prefix.name();
- if (typeNameIdentifier is PrefixedIdentifier) {
- var prefixed = typeNameIdentifier;
- // new prefix.ClassName()
- if (prefixed.prefix.staticElement is PrefixElement) {
- return prefixed.identifier.name;
- }
- // new ClassName.constructorName()
- return prefixed.prefix.name;
- }
+ // new ClassName.constructorName()
+ return prefixed.prefix.name;
}
} else if (expression is IndexExpression) {
name = _getBaseNameFromExpression(expression.realTarget);
@@ -966,7 +935,7 @@
/// Given a list of [imports] that do, or can, make the [name] visible in
/// scope, return the one that will lead to the cleanest code.
- ImportElement _getBestImportForName(
+ ImportElement? _getBestImportForName(
List<ImportElement> imports, String name) {
if (imports.isEmpty) {
return null;
@@ -992,7 +961,7 @@
}
/// Returns all variants of names by removing leading words one by one.
- List<String> _getCamelWordCombinations(String name) {
+ List<String> _getCamelWordCombinations(String? name) {
var result = <String>[];
var parts = getCamelWords(name);
for (var i = 0; i < parts.length; i++) {
@@ -1023,8 +992,8 @@
/// Returns possible names for a variable with the given expected type and
/// expression assigned.
- List<String> _getVariableNameSuggestionsForExpression(DartType expectedType,
- Expression assignedExpression, Set<String> excluded) {
+ List<String> _getVariableNameSuggestionsForExpression(DartType? expectedType,
+ Expression? assignedExpression, Set<String> excluded) {
var res = <String>{};
// use expression
if (assignedExpression != null) {
@@ -1059,8 +1028,8 @@
/// [_enclosingClass], or if there is a local equivalent to the type (such as
/// in the case of a type parameter from a superclass), then return the type
/// that is locally visible. Otherwise, return `null`.
- DartType _getVisibleType(DartType type,
- {ExecutableElement methodBeingCopied}) {
+ DartType? _getVisibleType(DartType? type,
+ {ExecutableElement? methodBeingCopied}) {
if (type is InterfaceType) {
var element = type.element;
if (element.isPrivate &&
@@ -1075,7 +1044,7 @@
var enclosing = element.enclosingElement;
while (enclosing is GenericFunctionTypeElement ||
enclosing is ParameterElement) {
- enclosing = enclosing.enclosingElement;
+ enclosing = enclosing!.enclosingElement;
}
if (enclosing == _enclosingExecutable ||
enclosing == _enclosingClass ||
@@ -1119,16 +1088,20 @@
var import = dartFileEditBuilder._getImportElement(element);
if (import != null) {
- if (import.prefix != null) {
- write(import.prefix.displayName);
+ var prefix = import.prefix;
+ if (prefix != null) {
+ write(prefix.displayName);
write('.');
}
} else {
- var library = element.library.source.uri;
- var import = dartFileEditBuilder._importLibrary(library);
- if (import.prefix != null) {
- write(import.prefix);
- write('.');
+ var library = element.library?.source.uri;
+ if (library != null) {
+ var import = dartFileEditBuilder._importLibrary(library);
+ var prefix = import.prefix;
+ if (prefix != null) {
+ write(prefix);
+ write('.');
+ }
}
}
}
@@ -1158,8 +1131,8 @@
///
/// Causes any libraries whose elements are used by the generated code, to be
/// imported.
- bool _writeType(DartType type,
- {ExecutableElement methodBeingCopied, bool required = false}) {
+ bool _writeType(DartType? type,
+ {ExecutableElement? methodBeingCopied, bool required = false}) {
type = _getVisibleType(type, methodBeingCopied: methodBeingCopied);
// If not a useful type, don't write it.
@@ -1183,10 +1156,11 @@
}
var aliasElement = type.aliasElement;
- if (aliasElement != null) {
+ var aliasArguments = type.aliasArguments;
+ if (aliasElement != null && aliasArguments != null) {
_writeTypeElementArguments(
element: aliasElement,
- typeArguments: type.aliasArguments,
+ typeArguments: aliasArguments,
methodBeingCopied: methodBeingCopied,
);
_writeTypeNullability(type);
@@ -1235,9 +1209,9 @@
}
void _writeTypeElementArguments({
- @required Element element,
- @required List<DartType> typeArguments,
- @required ExecutableElement methodBeingCopied,
+ required Element element,
+ required List<DartType> typeArguments,
+ required ExecutableElement? methodBeingCopied,
}) {
// Ensure that the element is imported.
_writeLibraryReference(element);
@@ -1288,10 +1262,10 @@
/// The change builder for the library
/// or `null` if the receiver is the builder for the library.
- final DartFileEditBuilderImpl libraryChangeBuilder;
+ final DartFileEditBuilderImpl? libraryChangeBuilder;
/// The optional generator of prefixes for new imports.
- ImportPrefixGenerator importPrefixGenerator;
+ ImportPrefixGenerator? importPrefixGenerator;
/// A mapping from libraries that need to be imported in order to make visible
/// the names used in generated code, to information about these imports.
@@ -1307,7 +1281,7 @@
/// the given [resolvedUnit] and [timeStamp].
DartFileEditBuilderImpl(ChangeBuilderImpl changeBuilder, this.resolvedUnit,
int timeStamp, this.libraryChangeBuilder)
- : super(changeBuilder, resolvedUnit.path, timeStamp);
+ : super(changeBuilder, resolvedUnit.path!, timeStamp);
@override
bool get hasEdits =>
@@ -1329,8 +1303,8 @@
@override
void convertFunctionFromSyncToAsync(
- FunctionBody body, TypeProvider typeProvider) {
- if (body == null && body.keyword != null) {
+ FunctionBody? body, TypeProvider typeProvider) {
+ if (body == null || body.keyword != null) {
throw ArgumentError(
'The function must have a synchronous, non-generator body.');
}
@@ -1379,7 +1353,7 @@
@override
void format(SourceRange range) {
- var newContent = resolvedUnit.content;
+ var newContent = resolvedUnit.content!;
var newRangeOffset = range.offset;
var newRangeLength = range.length;
for (var edit in fileEdit.edits) {
@@ -1434,13 +1408,13 @@
return ImportLibraryElementResultImpl(null);
}
- String importLibraryWithRelativeUri(String uriText, [String prefix]) {
+ String importLibraryWithRelativeUri(String uriText, [String? prefix]) {
return _importLibraryWithRelativeUri(uriText, prefix).uriText;
}
@override
void replaceTypeWithFuture(
- TypeAnnotation typeAnnotation, TypeProvider typeProvider) {
+ TypeAnnotation? typeAnnotation, TypeProvider typeProvider) {
//
// Check whether the type needs to be replaced.
//
@@ -1449,7 +1423,7 @@
return;
}
- addReplacement(range.node(typeAnnotation), (EditBuilder builder) {
+ addReplacement(range.node(typeAnnotation!), (EditBuilder builder) {
var futureType = typeProvider.futureType(type);
if (!(builder as DartEditBuilder).writeType(futureType)) {
builder.write('void');
@@ -1460,10 +1434,11 @@
/// Adds edits ensure that all the [imports] are imported into the library.
void _addLibraryImports(Iterable<_LibraryToImport> imports) {
// Prepare information about existing imports.
- LibraryDirective libraryDirective;
+ LibraryDirective? libraryDirective;
var importDirectives = <ImportDirective>[];
- PartDirective partDirective;
- for (var directive in resolvedUnit.unit.directives) {
+ PartDirective? partDirective;
+ var unit = resolvedUnit.unit!;
+ for (var directive in unit.directives) {
if (directive is LibraryDirective) {
libraryDirective = directive;
} else if (directive is ImportDirective) {
@@ -1481,9 +1456,10 @@
builder.write("import '");
builder.write(import.uriText);
builder.write("'");
- if (import.prefix != null) {
+ var prefix = import.prefix;
+ if (prefix != null) {
builder.write(' as ');
- builder.write(import.prefix);
+ builder.write(prefix);
}
builder.write(';');
}
@@ -1496,14 +1472,14 @@
var inserted = false;
void insert(
- {ImportDirective prev,
- ImportDirective next,
+ {ImportDirective? prev,
+ required ImportDirective next,
bool trailingNewLine = false}) {
var lineInfo = resolvedUnit.lineInfo;
if (prev != null) {
var offset = prev.end;
var line = lineInfo.getLocation(offset).lineNumber;
- Token comment = prev.endToken.next.precedingComments;
+ Token? comment = prev.endToken.next?.precedingComments;
while (comment != null) {
if (lineInfo.getLocation(comment.offset).lineNumber == line) {
offset = comment.end;
@@ -1534,9 +1510,9 @@
inserted = true;
}
- ImportDirective lastExisting;
- ImportDirective lastExistingDart;
- ImportDirective lastExistingPackage;
+ ImportDirective? lastExisting;
+ ImportDirective? lastExistingDart;
+ ImportDirective? lastExistingPackage;
var isLastExistingDart = false;
var isLastExistingPackage = false;
for (var existingImport in importDirectives) {
@@ -1581,7 +1557,7 @@
isLastExistingPackage = isExistingPackage;
}
if (!inserted) {
- addInsertion(lastExisting.end, (EditBuilder builder) {
+ addInsertion(lastExisting!.end, (EditBuilder builder) {
if (isPackage) {
if (isLastExistingDart) {
builder.writeln();
@@ -1631,11 +1607,11 @@
// If still at the beginning of the file, add before the first declaration.
int offset;
var insertEmptyLineAfter = false;
- if (resolvedUnit.unit.declarations.isNotEmpty) {
- offset = resolvedUnit.unit.declarations.first.offset;
+ if (unit.declarations.isNotEmpty) {
+ offset = unit.declarations.first.offset;
insertEmptyLineAfter = true;
} else {
- offset = resolvedUnit.unit.end;
+ offset = unit.end;
}
addInsertion(offset, (EditBuilder builder) {
for (var i = 0; i < importList.length; i++) {
@@ -1652,7 +1628,7 @@
/// Return the import element used to import the given [element] into the
/// target library, or `null` if the element was not imported, such as when
/// the element is declared in the same library.
- ImportElement _getImportElement(Element element) {
+ ImportElement? _getImportElement(Element element) {
for (var import in resolvedUnit.libraryElement.imports) {
var definedNames = import.namespace.definedNames;
if (definedNames.containsValue(element)) {
@@ -1664,7 +1640,7 @@
Iterable<ImportElement> _getImportsForUri(Uri uri) sync* {
for (var import in resolvedUnit.libraryElement.imports) {
- var importUri = import.importedLibrary.source.uri;
+ var importUri = import.importedLibrary?.source.uri;
if (importUri == uri) {
yield import;
}
@@ -1690,7 +1666,7 @@
if (import == null) {
var uriText = _getLibraryUriText(uri);
var prefix =
- importPrefixGenerator != null ? importPrefixGenerator(uri) : null;
+ importPrefixGenerator != null ? importPrefixGenerator!(uri) : null;
import = _LibraryToImport(uriText, prefix);
(libraryChangeBuilder ?? this).librariesToImport[uri] = import;
}
@@ -1700,7 +1676,7 @@
/// Arrange to have an import added for the library with the given relative
/// [uriText].
_LibraryToImport _importLibraryWithRelativeUri(String uriText,
- [String prefix]) {
+ [String? prefix]) {
var import = librariesToRelativelyImport[uriText];
if (import == null) {
import = _LibraryToImport(uriText, prefix);
@@ -1718,7 +1694,7 @@
/// containing the given [node] with the type `Future`. The [typeProvider] is
/// used to check the current return type, because if it is already `Future`
/// no edit will be added.
- void _replaceReturnTypeWithFuture(AstNode node, TypeProvider typeProvider) {
+ void _replaceReturnTypeWithFuture(AstNode? node, TypeProvider typeProvider) {
while (node != null) {
node = node.parent;
if (node is FunctionDeclaration) {
@@ -1736,7 +1712,7 @@
}
static bool _isFusedWithPreviousToken(Token token) {
- return token.previous.end == token.offset;
+ return token.previous?.end == token.offset;
}
}
@@ -1749,13 +1725,13 @@
DartLinkedEditBuilderImpl(EditBuilderImpl editBuilder) : super(editBuilder);
@override
- void addSuperTypesAsSuggestions(DartType type) {
+ void addSuperTypesAsSuggestions(DartType? type) {
_addSuperTypesAsSuggestions(type, <DartType>{});
}
/// Safely implement [addSuperTypesAsSuggestions] by using the set of
/// [alreadyAdded] types to prevent infinite loops.
- void _addSuperTypesAsSuggestions(DartType type, Set<DartType> alreadyAdded) {
+ void _addSuperTypesAsSuggestions(DartType? type, Set<DartType> alreadyAdded) {
if (type is InterfaceType && alreadyAdded.add(type)) {
addSuggestion(
LinkedEditSuggestionKind.TYPE,
@@ -1772,18 +1748,18 @@
/// Information about a library to import.
class ImportLibraryElementResultImpl implements ImportLibraryElementResult {
@override
- final String prefix;
+ final String? prefix;
ImportLibraryElementResultImpl(this.prefix);
}
class _EnclosingElementFinder {
- ClassElement enclosingClass;
- ExecutableElement enclosingExecutable;
+ ClassElement? enclosingClass;
+ ExecutableElement? enclosingExecutable;
_EnclosingElementFinder();
- void find(AstNode target, int offset) {
+ void find(AstNode? target, int offset) {
var node = NodeLocator2(offset).searchWithin(target);
while (node != null) {
if (node is ClassDeclaration) {
@@ -1803,7 +1779,7 @@
/// Information about a new library to import.
class _LibraryToImport {
final String uriText;
- final String prefix;
+ final String? prefix;
_LibraryToImport(this.uriText, this.prefix);
diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/completion_core.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/completion_core.dart
index a2e052a..b0e6bdc 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/completion/completion_core.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/completion/completion_core.dart
@@ -11,11 +11,11 @@
class CompletionCollectorImpl implements CompletionCollector {
/// The length of the region of text that should be replaced by the selected
/// completion suggestion.
- int _length;
+ int? _length;
/// The offset of the region of text that should be replaced by the selected
/// completion suggestion.
- int _offset;
+ int? _offset;
/// A list of the completion suggestions that have been collected.
List<CompletionSuggestion> suggestions = <CompletionSuggestion>[];
@@ -25,10 +25,10 @@
/// Return the length of the region of text that should be replaced by the
/// selected completion suggestion, or `null` if the length has not been set.
- int get length => _length;
+ int? get length => _length;
@override
- set length(int length) {
+ set length(int? length) {
if (_length != null) {
throw StateError('The length can only be set once');
}
@@ -37,10 +37,10 @@
/// Return the offset of the region of text that should be replaced by the
/// selected completion suggestion, or `null` if the offset has not been set.
- int get offset => _offset;
+ int? get offset => _offset;
@override
- set offset(int length) {
+ set offset(int? length) {
if (_offset != null) {
throw StateError('The offset can only be set once');
}
diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/completion_target.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/completion_target.dart
index 0b47a56..4781140 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/completion/completion_target.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/completion/completion_target.dart
@@ -86,7 +86,7 @@
/// or keyword that is part of the token stream, but that the parser has
/// skipped and not reported in to the parser listeners, meaning that it is
/// not part of the AST.
- Token droppedToken;
+ Token? droppedToken;
/// The entity which the completed text will replace (or which will be
/// displaced once the completed text is inserted). This may be an AstNode or
@@ -97,7 +97,7 @@
/// possible). However, there is one exception: when the cursor is inside of
/// a multi-character token which is not a keyword or identifier (e.g. a
/// comment, or a token like "+=", the entity will be always be the token.
- final SyntacticEntity entity;
+ final SyntacticEntity? entity;
/// The [entity] is a comment token, which is either not a documentation
/// comment or the position is not in a [CommentReference].
@@ -105,21 +105,21 @@
/// If the target is an argument in an [ArgumentList], then this is the index
/// of the argument in the list, otherwise this is `null`.
- final int argIndex;
+ final int? argIndex;
/// If the target is an argument in an [ArgumentList], then this is the
/// invoked [ExecutableElement], otherwise this is `null`.
- ExecutableElement _executableElement;
+ ExecutableElement? _executableElement;
/// If the target is in an argument list of a [FunctionExpressionInvocation],
/// then this is the static type of the function being invoked, otherwise this
/// is `null`.
- FunctionType _functionType;
+ FunctionType? _functionType;
/// If the target is an argument in an [ArgumentList], then this is the
/// corresponding [ParameterElement] in the invoked [ExecutableElement],
/// otherwise this is `null`.
- ParameterElement _parameterElement;
+ ParameterElement? _parameterElement;
/// Compute the appropriate [CompletionTarget] for the given [offset] within
/// the [compilationUnit].
@@ -129,7 +129,7 @@
/// [compilationUnit] such as dart expressions within angular templates.
factory CompletionTarget.forOffset(
CompilationUnit compilationUnit, int offset,
- {AstNode entryPoint}) {
+ {AstNode? entryPoint}) {
// The precise algorithm is as follows. We perform a depth-first search of
// all edges in the parse tree (both those that point to AST nodes and
// those that point to tokens), visiting parents before children. The
@@ -151,7 +151,7 @@
if (containingNode is Comment) {
// Comments are handled specially: we descend into any CommentReference
// child node that contains the cursor offset.
- var comment = containingNode as Comment;
+ var comment = containingNode;
for (var commentReference in comment.references) {
if (commentReference.offset <= offset &&
offset <= commentReference.end) {
@@ -245,7 +245,7 @@
/// Create a [CompletionTarget] holding the given [containingNode] and
/// [entity].
CompletionTarget._(this.unit, this.offset, AstNode containingNode,
- SyntacticEntity entity, this.isCommentText)
+ SyntacticEntity? entity, this.isCommentText)
: containingNode = containingNode,
entity = entity,
argIndex = _computeArgIndex(containingNode, entity),
@@ -253,9 +253,9 @@
/// If the target is an argument in an argument list, and the invocation is
/// resolved, return the invoked [ExecutableElement].
- ExecutableElement get executableElement {
+ ExecutableElement? get executableElement {
if (_executableElement == null) {
- var argumentList = containingNode;
+ AstNode? argumentList = containingNode;
if (argumentList is NamedExpression) {
argumentList = argumentList.parent;
}
@@ -265,7 +265,7 @@
var invocation = argumentList.parent;
- Element executable;
+ Element? executable;
if (invocation is Annotation) {
executable = invocation.element;
} else if (invocation is InstanceCreationExpression) {
@@ -286,9 +286,9 @@
/// If the target is in an argument list of a [FunctionExpressionInvocation],
/// then this is the static type of the function being invoked, otherwise this
/// is `null`.
- FunctionType get functionType {
+ FunctionType? get functionType {
if (_functionType == null) {
- var argumentList = containingNode;
+ AstNode? argumentList = containingNode;
if (argumentList is NamedExpression) {
argumentList = argumentList.parent;
}
@@ -319,14 +319,17 @@
return node.isCascaded && offset > node.operator.offset + 1;
}
if (node is MethodInvocation) {
- return node.isCascaded && offset > node.operator.offset + 1;
+ var operator = node.operator;
+ if (operator != null) {
+ return node.isCascaded && offset > operator.offset + 1;
+ }
}
return false;
}
/// If the target is an argument in an argument list, and the invocation is
/// resolved, return the corresponding [ParameterElement].
- ParameterElement get parameterElement {
+ ParameterElement? get parameterElement {
if (_parameterElement == null) {
var executable = executableElement;
if (executable != null) {
@@ -345,7 +348,7 @@
token.type.isKeyword || token.type == TokenType.IDENTIFIER;
var token = droppedToken ??
- (entity is AstNode ? (entity as AstNode).beginToken : entity as Token);
+ (entity is AstNode ? (entity as AstNode).beginToken : entity as Token?);
if (token != null && requestOffset < token.offset) {
token = containingNode.findPrevious(token);
}
@@ -399,7 +402,7 @@
/// Given that the [node] contains the [offset], return the [FormalParameter]
/// that encloses the [offset], or `null`.
- static FormalParameter findFormalParameter(
+ static FormalParameter? findFormalParameter(
FormalParameterList node,
int offset,
) {
@@ -423,8 +426,8 @@
return null;
}
- static int _computeArgIndex(AstNode containingNode, Object entity) {
- var argList = containingNode;
+ static int? _computeArgIndex(AstNode containingNode, Object? entity) {
+ AstNode? argList = containingNode;
if (argList is NamedExpression) {
entity = argList;
argList = argList.parent;
@@ -451,8 +454,8 @@
return null;
}
- static Token _computeDroppedToken(
- AstNode containingNode, Object entity, int offset) {
+ static Token? _computeDroppedToken(
+ AstNode containingNode, Object? entity, int offset) {
// Find the last token of the member before the entity.
var previousMember;
for (var member in containingNode.childEntities) {
@@ -463,7 +466,7 @@
previousMember = member;
}
}
- Token token;
+ Token? token;
if (previousMember is AstNode) {
token = previousMember.endToken;
} else if (previousMember is Token) {
@@ -474,7 +477,7 @@
}
// Find the first token of the entity (which may be the entity itself).
- Token endSearch;
+ Token? endSearch;
if (entity is AstNode) {
endSearch = entity.beginToken;
} else if (entity is Token) {
@@ -486,7 +489,7 @@
// Find a dropped token that overlaps the offset.
token = token.next;
- while (token != endSearch && !token.isEof) {
+ while (token != endSearch && !token!.isEof) {
if (token.isKeywordOrIdentifier &&
token.offset <= offset &&
offset <= token.end) {
@@ -499,7 +502,7 @@
/// Determine if the offset is contained in a preceding comment token
/// and return that token, otherwise return `null`.
- static Token _getContainingCommentToken(Token token, int offset) {
+ static Token? _getContainingCommentToken(Token? token, int offset) {
if (token == null) {
return null;
}
@@ -522,7 +525,7 @@
}
/// Determine if the given token is part of the given node's dart doc.
- static Comment _getContainingDocComment(AstNode node, Token token) {
+ static Comment? _getContainingDocComment(AstNode node, Token token) {
if (node is AnnotatedNode) {
var docComment = node.documentationComment;
if (docComment != null && docComment.tokens.contains(token)) {
@@ -534,13 +537,13 @@
/// Return the [ParameterElement] that corresponds to the given [argumentNode]
/// at the given [argumentIndex].
- static ParameterElement _getParameterElement(
+ static ParameterElement? _getParameterElement(
List<ParameterElement> parameters,
AstNode argumentNode,
- int argumentIndex,
+ int? argumentIndex,
) {
if (argumentNode is NamedExpression) {
- var name = argumentNode.name?.label?.name;
+ var name = argumentNode.name.label.name;
for (var parameter in parameters) {
if (parameter.name == name) {
return parameter;
@@ -549,7 +552,7 @@
return null;
}
- if (argumentIndex < parameters.length) {
+ if (argumentIndex != null && argumentIndex < parameters.length) {
return parameters[argumentIndex];
}
@@ -575,7 +578,7 @@
/// Determine whether [token] could possibly be the [entity] for a
/// [CompletionTarget] associated with the given [offset].
- static bool _isCandidateToken(AstNode node, Token token, int offset) {
+ static bool _isCandidateToken(AstNode node, Token? token, int offset) {
if (token == null) {
return false;
}
diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart
index 298c5b5..127cb49 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/completion/element_suggestion_builder.dart
@@ -24,17 +24,17 @@
<String, CompletionSuggestion>{};
/// Return the library in which the completion is requested.
- LibraryElement get containingLibrary;
+ LibraryElement? get containingLibrary;
/// Return the kind of suggestions that should be built.
- CompletionSuggestionKind get kind;
+ CompletionSuggestionKind? get kind;
/// Return the resource provider used to access the file system.
- ResourceProvider get resourceProvider;
+ ResourceProvider? get resourceProvider;
/// Add a suggestion based upon the given element.
void addSuggestion(Element element,
- {String prefix, int relevance = DART_RELEVANCE_DEFAULT}) {
+ {String? prefix, int relevance = DART_RELEVANCE_DEFAULT}) {
if (element.isPrivate) {
if (element.library != containingLibrary) {
return;
@@ -42,13 +42,13 @@
}
var completion = element.displayName;
if (prefix != null && prefix.isNotEmpty) {
- if (completion == null || completion.isEmpty) {
+ if (completion.isEmpty) {
completion = prefix;
} else {
completion = '$prefix.$completion';
}
}
- if (completion == null || completion.isEmpty) {
+ if (completion.isEmpty) {
return;
}
var builder = SuggestionBuilderImpl(resourceProvider);
@@ -56,7 +56,7 @@
completion: completion, kind: kind, relevance: relevance);
if (suggestion != null) {
if (element.isSynthetic && element is PropertyAccessorElement) {
- String cacheKey;
+ String? cacheKey;
if (element.isGetter) {
cacheKey = element.name;
}
@@ -75,10 +75,10 @@
: protocol.ElementKind.TOP_LEVEL_VARIABLE;
existingSuggestion.element = protocol.Element(
elemKind,
- existingSuggestion.element.name,
- existingSuggestion.element.flags,
- location: getter.element.location,
- typeParameters: getter.element.typeParameters,
+ existingSuggestion.element!.name,
+ existingSuggestion.element!.flags,
+ location: getter.element?.location,
+ typeParameters: getter.element?.typeParameters,
parameters: null,
returnType: getter.returnType);
return;
diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart
index ae49588..7148d29 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/completion/optype.dart
@@ -1,7 +1,6 @@
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart';
import 'package:analyzer/dart/ast/token.dart';
@@ -13,15 +12,16 @@
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer_plugin/protocol/protocol_common.dart' hide Element;
import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
+import 'package:collection/collection.dart';
-typedef SuggestionsFilter = int Function(DartType dartType, int relevance);
+typedef SuggestionsFilter = int? Function(DartType dartType, int relevance);
/// An [AstVisitor] for determining whether top level suggestions or invocation
/// suggestions should be made based upon the type of node in which the
/// suggestions were requested.
class OpType {
/// The [TypeSystem] used during resolution of the current unit.
- TypeSystem _typeSystem;
+ TypeSystem? _typeSystem;
/// Indicates whether constructor suggestions should be included.
bool includeConstructorSuggestions = false;
@@ -74,11 +74,11 @@
CompletionSuggestionKind suggestKind = CompletionSuggestionKind.INVOCATION;
/// An representation of the location at which completion was requested.
- String completionLocation;
+ String? completionLocation;
/// The type that is required by the context in which the completion was
/// activated, or `null` if there is no such type, or it cannot be determined.
- DartType _requiredType;
+ DartType? _requiredType;
/// Determine the suggestions that should be made based upon the given
/// [CompletionTarget] and [offset].
@@ -90,7 +90,7 @@
return optype;
}
- optype._typeSystem = target.unit?.declaredElement?.library?.typeSystem;
+ optype._typeSystem = target.unit.declaredElement?.library.typeSystem;
var targetNode = target.containingNode;
targetNode.accept(_OpTypeAstVisitor(optype, target.entity, offset));
@@ -112,7 +112,7 @@
// If a value should be suggested, suggest also constructors.
if (optype.includeReturnValueSuggestions) {
// Careful: in angular plugin, `target.unit` may be null!
- var unitElement = target.unit?.declaredElement;
+ var unitElement = target.unit.declaredElement;
if (unitElement != null) {
optype.includeConstructorSuggestions = true;
}
@@ -145,7 +145,7 @@
/// Try to determine the required context type, and configure filters.
void _computeRequiredTypeAndFilters(CompletionTarget target) {
var entity = target.entity;
- var node = target.containingNode;
+ AstNode? node = target.containingNode;
if (node is InstanceCreationExpression &&
node.keyword != null &&
@@ -157,28 +157,29 @@
if (node is AssignmentExpression &&
node.operator.type == TokenType.EQ &&
node.rightHandSide == entity) {
- _requiredType = node.leftHandSide?.staticType;
+ _requiredType = node.leftHandSide.staticType;
} else if (node is BinaryExpression &&
node.operator.type == TokenType.EQ_EQ &&
node.rightOperand == entity) {
- _requiredType = node.leftOperand?.staticType;
+ _requiredType = node.leftOperand.staticType;
} else if (node is NamedExpression && node.expression == entity) {
_requiredType = node.staticParameterElement?.type;
} else if (node is SwitchCase && node.expression == entity) {
var parent = node.parent;
if (parent is SwitchStatement) {
- _requiredType = parent.expression?.staticType;
+ _requiredType = parent.expression.staticType;
}
} else if (node is VariableDeclaration && node.initializer == entity) {
_requiredType = node.declaredElement?.type;
} else if (entity is Expression && entity.staticParameterElement != null) {
- _requiredType = entity.staticParameterElement.type;
+ _requiredType = entity.staticParameterElement?.type;
}
- if (_requiredType == null) {
+ var requiredType = _requiredType;
+ if (requiredType == null) {
return;
}
- if (_requiredType.isDynamic || _requiredType.isDartCoreObject) {
+ if (requiredType.isDynamic || requiredType.isDartCoreObject) {
_requiredType = null;
return;
}
@@ -186,16 +187,17 @@
/// Return `true` if the [leftType] is a subtype of the [rightType].
bool _isSubtypeOf(DartType leftType, DartType rightType) {
- if (_typeSystem == null) {
+ var typeSystem = _typeSystem;
+ if (typeSystem == null) {
return false;
}
- return _typeSystem.isSubtypeOf(leftType, rightType);
+ return typeSystem.isSubtypeOf(leftType, rightType);
}
/// Return the statement before [entity]
/// where [entity] can be a statement or the `}` closing the given block.
- static Statement getPreviousStatement(Block node, Object entity) {
+ static Statement? getPreviousStatement(Block node, Object? entity) {
if (entity == node.rightBracket) {
return node.statements.isNotEmpty ? node.statements.last : null;
}
@@ -213,7 +215,7 @@
class _OpTypeAstVisitor extends GeneralizingAstVisitor<void> {
/// The entity (AstNode or Token) that will be replaced or displaced by the
/// added text.
- final SyntacticEntity entity;
+ final SyntacticEntity? entity;
/// The offset within the source at which the completion is requested.
final int offset;
@@ -245,14 +247,14 @@
@override
void visitArgumentList(ArgumentList node) {
var parent = node.parent;
- List<ParameterElement> parameters;
+ List<ParameterElement>? parameters;
if (parent is InstanceCreationExpression) {
- Element constructor;
- var name = parent.constructorName?.name;
+ Element? constructor;
+ var name = parent.constructorName.name;
if (name != null) {
constructor = name.staticElement;
} else {
- var classElem = parent.constructorName?.type?.name?.staticElement;
+ var classElem = parent.constructorName.type.name.staticElement;
if (classElem is ClassElement) {
constructor = classElem.unnamedConstructor;
}
@@ -306,7 +308,7 @@
}
if (0 <= index && index < parameters.length) {
var param = parameters[index];
- if (param?.isNamed == true) {
+ if (param.isNamed == true) {
var context = _argumentListContext(node);
optype.completionLocation = 'ArgumentList_${context}_named';
optype.includeNamedArgumentSuggestions = true;
@@ -476,6 +478,7 @@
return node.end;
}
+ var entity = this.entity;
if (entity != null) {
if (entity.offset <= declarationStart()) {
optype.completionLocation = 'CompilationUnit_declaration';
@@ -522,14 +525,8 @@
// some PrefixedIdentifier nodes are transformed into
// ConstructorName nodes during the resolution process.
if (identical(entity, node.name)) {
- var type = node.type;
- if (type != null) {
- var prefix = type.name;
- if (prefix != null) {
- optype.includeConstructorSuggestions = true;
- optype.isPrefixed = true;
- }
- }
+ optype.includeConstructorSuggestions = true;
+ optype.isPrefixed = true;
}
}
@@ -659,8 +656,8 @@
@override
void visitForEachParts(ForEachParts node) {
if (identical(entity, node.inKeyword) && offset <= node.inKeyword.offset) {
- if (!(node is ForEachPartsWithIdentifier && node.identifier != null ||
- node is ForEachPartsWithDeclaration && node.loopVariable != null)) {
+ if (!(node is ForEachPartsWithIdentifier ||
+ node is ForEachPartsWithDeclaration)) {
optype.includeTypeNameSuggestions = true;
}
}
@@ -728,7 +725,7 @@
// Handle default normal parameter just as a normal parameter.
if (parameter is DefaultFormalParameter) {
- parameter = (parameter as DefaultFormalParameter).parameter;
+ parameter = parameter.parameter;
}
// "(^ this.field)"
@@ -955,7 +952,10 @@
@override
void visitMethodInvocation(MethodInvocation node) {
var isThis = node.target is ThisExpression;
- if (identical(entity, node.operator) && offset > node.operator.offset) {
+ var operator = node.operator;
+ if (operator != null &&
+ identical(entity, operator) &&
+ offset > operator.offset) {
// The cursor is between the two dots of a ".." token, so we need to
// generate the completions we would generate after a "." token.
optype.includeReturnValueSuggestions = true;
@@ -1004,17 +1004,17 @@
optype.includeTypeNameSuggestions = true;
// Check for named parameters in constructor calls.
- var grandparent = node.parent.parent;
+ var grandparent = node.parent?.parent;
if (grandparent is ConstructorReferenceNode) {
var element = grandparent.staticElement;
if (element != null) {
var parameters = element.parameters;
- var parameterElement = parameters.firstWhere((e) {
+ var parameterElement = parameters.firstWhereOrNull((e) {
if (e is DefaultFieldFormalParameterElementImpl) {
- return e.field?.name == node.name.label?.name;
+ return e.field?.name == node.name.label.name;
}
- return e.isNamed && e.name == node.name.label?.name;
- }, orElse: () => null);
+ return e.isNamed && e.name == node.name.label.name;
+ });
// Suggest tear-offs.
if (parameterElement?.type is FunctionType) {
optype.includeVoidReturnSuggestions = true;
@@ -1064,8 +1064,7 @@
// In addition to the standard case,
// handle the exceptional case where the parser considers the would-be
// identifier to be a keyword and inserts a synthetic identifier
- (node.identifier != null &&
- node.identifier.isSynthetic &&
+ (node.identifier.isSynthetic &&
identical(entity, node.findPrevious(node.identifier.beginToken)))) {
if (node.prefix.isSynthetic) {
// If the access has no target (empty string)
@@ -1073,7 +1072,7 @@
return;
}
optype.isPrefixed = true;
- if (node.parent is TypeName && node.parent.parent is ConstructorName) {
+ if (node.parent is TypeName && node.parent?.parent is ConstructorName) {
optype.includeConstructorSuggestions = true;
} else if (node.parent is Annotation) {
optype.includeConstructorSuggestions = true;
@@ -1162,15 +1161,18 @@
}
// If "(^ Type)", then include types.
- if (type == null && offset < name.offset) {
+ if (type == null && name != null && offset < name.offset) {
optype.includeTypeNameSuggestions = true;
return;
}
// If "(Type ^)", then include parameter names.
- if (type == null && name.end < offset && offset <= name.token.next.offset) {
- optype.includeVarNameSuggestions = true;
- return;
+ if (type == null && name != null && name.end < offset) {
+ var nextToken = name.token.next;
+ if (nextToken != null && offset <= nextToken.offset) {
+ optype.includeVarNameSuggestions = true;
+ return;
+ }
}
// If inside of "Type" in "(Type^ name)", then include types.
@@ -1332,7 +1334,7 @@
@override
void visitVariableDeclarationList(VariableDeclarationList node) {
- if (node.keyword == null || node.keyword.lexeme != 'var') {
+ if (node.keyword == null || node.keyword?.lexeme != 'var') {
if (node.type == null || identical(entity, node.type)) {
optype.completionLocation = 'VariableDeclarationList_type';
optype.includeTypeNameSuggestions = true;
@@ -1375,7 +1377,7 @@
/// Return the context in which the [node] occurs. The [node] is expected to
/// be the parent of the argument expression.
- String _argumentListContext(AstNode node) {
+ String _argumentListContext(AstNode? node) {
if (node is ArgumentList) {
var parent = node.parent;
if (parent is Annotation) {
@@ -1406,7 +1408,7 @@
return 'index';
}
throw ArgumentError(
- 'Unknown parent of ${node.runtimeType}: ${node.parent.runtimeType}');
+ 'Unknown parent of ${node.runtimeType}: ${node?.parent.runtimeType}');
}
bool _isEntityPrevTokenSynthetic() {
@@ -1422,7 +1424,7 @@
/// A filter used to disable everything except classes (such as functions and
/// mixins).
- int _nonMixinClasses(DartType type, int relevance) {
+ int? _nonMixinClasses(DartType type, int relevance) {
if (type is InterfaceType) {
if (type.element.isMixin) {
return null;
diff --git a/pkg/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart b/pkg/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart
index 946ad5b..e452d3d 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/completion/suggestion_builder.dart
@@ -14,7 +14,7 @@
/// An object used to build code completion suggestions for Dart code.
class SuggestionBuilderImpl implements SuggestionBuilder {
/// The resource provider used to access the file system.
- final ResourceProvider resourceProvider;
+ final ResourceProvider? resourceProvider;
/// The converter used to convert analyzer objects to protocol objects.
final AnalyzerConverter converter = AnalyzerConverter();
@@ -65,9 +65,9 @@
}
@override
- CompletionSuggestion forElement(Element element,
- {String completion,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ CompletionSuggestion? forElement(Element? element,
+ {String? completion,
+ CompletionSuggestionKind? kind,
int relevance = DART_RELEVANCE_DEFAULT}) {
// Copied from analysis_server/lib/src/services/completion/dart/suggestion_builder.dart
if (element == null) {
@@ -80,7 +80,7 @@
completion ??= element.displayName;
var isDeprecated = element.hasDeprecated;
var suggestion = CompletionSuggestion(
- kind,
+ kind ?? CompletionSuggestionKind.INVOCATION,
isDeprecated ? DART_RELEVANCE_LOW : relevance,
completion,
completion.length,
@@ -105,11 +105,7 @@
.toList();
suggestion.parameterTypes =
element.parameters.map((ParameterElement parameter) {
- var paramType = parameter.type;
- // Gracefully degrade if type not resolved yet
- return paramType != null
- ? paramType.getDisplayString(withNullability: false)
- : 'var';
+ return parameter.type.getDisplayString(withNullability: false);
}).toList();
var requiredParameters = element.parameters
@@ -126,19 +122,17 @@
return suggestion;
}
- String getReturnTypeString(Element element) {
+ String? getReturnTypeString(Element element) {
// Copied from analysis_server/lib/src/protocol_server.dart
if (element is ExecutableElement) {
if (element.kind == ElementKind.SETTER) {
return null;
} else {
- return element.returnType?.getDisplayString(withNullability: false);
+ return element.returnType.getDisplayString(withNullability: false);
}
} else if (element is VariableElement) {
var type = element.type;
- return type != null
- ? type.getDisplayString(withNullability: false)
- : 'dynamic';
+ return type.getDisplayString(withNullability: false);
} else if (element is TypeAliasElement) {
var aliasedElement = element.aliasedElement;
if (aliasedElement is GenericFunctionTypeElement) {
diff --git a/pkg/analyzer_plugin/lib/src/utilities/documentation.dart b/pkg/analyzer_plugin/lib/src/utilities/documentation.dart
index 50299be..69dcb9b 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/documentation.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/documentation.dart
@@ -4,7 +4,7 @@
/// Return the summary of the given DartDoc [string], which is the content of
/// the lines before the first blank line.
-String getDartDocSummary(String string) {
+String? getDartDocSummary(String? string) {
if (string == null) {
return null;
}
@@ -26,7 +26,7 @@
/// Converts [string] from a DartDoc comment with slashes and stars to a plain
/// text representation of the comment.
-String removeDartDocDelimiters(String string) {
+String? removeDartDocDelimiters(String? string) {
if (string == null) {
return null;
}
diff --git a/pkg/analyzer_plugin/lib/src/utilities/folding/folding.dart b/pkg/analyzer_plugin/lib/src/utilities/folding/folding.dart
index d424abf..a302a76 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/folding/folding.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/folding/folding.dart
@@ -21,7 +21,7 @@
DartFoldingRequestImpl(this.resourceProvider, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [FoldingCollector].
diff --git a/pkg/analyzer_plugin/lib/src/utilities/highlights/highlights.dart b/pkg/analyzer_plugin/lib/src/utilities/highlights/highlights.dart
index 95bd889..5e55b48 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/highlights/highlights.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/highlights/highlights.dart
@@ -21,7 +21,7 @@
DartHighlightsRequestImpl(this.resourceProvider, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [HighlightsCollector].
diff --git a/pkg/analyzer_plugin/lib/src/utilities/kythe/entries.dart b/pkg/analyzer_plugin/lib/src/utilities/kythe/entries.dart
index 684e9e7..191101c 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/kythe/entries.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/kythe/entries.dart
@@ -19,7 +19,7 @@
DartEntryRequestImpl(this.resourceProvider, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [EntryCollector].
diff --git a/pkg/analyzer_plugin/lib/src/utilities/navigation/navigation.dart b/pkg/analyzer_plugin/lib/src/utilities/navigation/navigation.dart
index c660f85..4e1850c 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/navigation/navigation.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/navigation/navigation.dart
@@ -28,7 +28,7 @@
this.resourceProvider, this.offset, this.length, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [NavigationCollector].
@@ -59,7 +59,7 @@
@override
void addRange(
SourceRange range, ElementKind targetKind, Location targetLocation,
- {Location targetCodeLocation}) {
+ {Location? targetCodeLocation}) {
addRegion(range.offset, range.length, targetKind, targetLocation,
targetCodeLocation: targetCodeLocation);
}
@@ -67,7 +67,7 @@
@override
void addRegion(
int offset, int length, ElementKind targetKind, Location targetLocation,
- {Location targetCodeLocation}) {
+ {Location? targetCodeLocation}) {
var range = SourceRange(offset, length);
// add new target
var targets = regionMap.putIfAbsent(range, () => <int>[]);
@@ -96,7 +96,7 @@
return index;
}
- int _addTarget(ElementKind kind, Location location, Location codeLocation) {
+ int _addTarget(ElementKind kind, Location location, Location? codeLocation) {
var pair = Pair<ElementKind, Location>(kind, location);
var index = targetMap[pair];
if (index == null) {
diff --git a/pkg/analyzer_plugin/lib/src/utilities/null_string_sink.dart b/pkg/analyzer_plugin/lib/src/utilities/null_string_sink.dart
index ec2cc26..012bb11 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/null_string_sink.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/null_string_sink.dart
@@ -5,7 +5,7 @@
/// A string sink that ignores everything written to it.
class NullStringSink implements StringSink {
@override
- void write(Object obj) {}
+ void write(Object? obj) {}
@override
void writeAll(Iterable objects, [String separator = '']) {}
@@ -14,5 +14,5 @@
void writeCharCode(int charCode) {}
@override
- void writeln([Object obj = '']) {}
+ void writeln([Object? obj = '']) {}
}
diff --git a/pkg/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart b/pkg/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart
index f436774..6bd0592 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/occurrences/occurrences.dart
@@ -20,7 +20,7 @@
DartOccurrencesRequestImpl(this.resourceProvider, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [OccurrencesCollector].
diff --git a/pkg/analyzer_plugin/lib/src/utilities/outline/outline.dart b/pkg/analyzer_plugin/lib/src/utilities/outline/outline.dart
index 284f140..44d4dd9 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/outline/outline.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/outline/outline.dart
@@ -20,7 +20,7 @@
DartOutlineRequestImpl(this.resourceProvider, this.result);
@override
- String get path => result.path;
+ String get path => result.path!;
}
/// A concrete implementation of [OutlineCollector].
diff --git a/pkg/analyzer_plugin/lib/src/utilities/string_utilities.dart b/pkg/analyzer_plugin/lib/src/utilities/string_utilities.dart
index 9575749..7c8d1be 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/string_utilities.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/string_utilities.dart
@@ -9,7 +9,7 @@
///
/// 'getCamelWords' => ['get', 'Camel', 'Words']
/// 'getHTMLText' => ['get', 'HTML', 'Text']
-List<String> getCamelWords(String string) {
+List<String> getCamelWords(String? string) {
if (string == null || string.isEmpty) {
return const <String>[];
}
@@ -44,7 +44,7 @@
}
/// Return `true` if the given [string] is either `null` or empty.
-bool isEmpty(String string) => string == null || string.isEmpty;
+bool isEmpty(String? string) => string == null || string.isEmpty;
/// Return `true` if the given [character] is a lowercase ASCII character.
bool isLowerCase(int character) => character >= $a && character <= $z;
@@ -55,8 +55,11 @@
/// If the given [string] starts with the text to [remove], then return the
/// portion of the string after the text to remove. Otherwise, return the
/// original string unmodified.
-String removeStart(String string, String remove) {
- if (isEmpty(string) || isEmpty(remove)) {
+String? removeStart(String? string, String? remove) {
+ if (string == null || string.isEmpty) {
+ return string;
+ }
+ if (remove == null || remove.isEmpty) {
return string;
}
if (string.startsWith(remove)) {
diff --git a/pkg/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart b/pkg/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart
index c561be1..a7ea9aa 100644
--- a/pkg/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart
+++ b/pkg/analyzer_plugin/lib/src/utilities/visitors/local_declaration_visitor.dart
@@ -41,13 +41,13 @@
void declaredLabel(Label label, bool isCaseLabel) {}
- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) {}
+ void declaredLocalVar(SimpleIdentifier name, TypeAnnotation? type) {}
void declaredMethod(MethodDeclaration declaration) {}
void declaredMixin(MixinDeclaration declaration) {}
- void declaredParam(SimpleIdentifier name, TypeAnnotation type) {}
+ void declaredParam(SimpleIdentifier name, TypeAnnotation? type) {}
void declaredTopLevelVar(
VariableDeclarationList varList, VariableDeclaration varDecl) {}
@@ -116,11 +116,9 @@
declaredLocalVar(loopVariable.identifier, loopVariable.type);
} else if (forLoopParts is ForPartsWithDeclarations) {
var varList = forLoopParts.variables;
- if (varList != null) {
- varList.variables.forEach((VariableDeclaration varDecl) {
- declaredLocalVar(varDecl.name, varList.type);
- });
- }
+ varList.variables.forEach((VariableDeclaration varDecl) {
+ declaredLocalVar(varDecl.name, varList.type);
+ });
}
visitNode(node);
}
@@ -133,11 +131,9 @@
declaredLocalVar(loopVariable.identifier, loopVariable.type);
} else if (forLoopParts is ForPartsWithDeclarations) {
var varList = forLoopParts.variables;
- if (varList != null) {
- varList.variables.forEach((VariableDeclaration varDecl) {
- declaredLocalVar(varDecl.name, varList.type);
- });
- }
+ varList.variables.forEach((VariableDeclaration varDecl) {
+ declaredLocalVar(varDecl.name, varList.type);
+ });
}
visitNode(node);
}
@@ -255,11 +251,9 @@
);
} else if (declaration is TopLevelVariableDeclaration) {
var varList = declaration.variables;
- if (varList != null) {
- varList.variables.forEach((VariableDeclaration varDecl) {
- declaredTopLevelVar(varList, varDecl);
- });
- }
+ varList.variables.forEach((VariableDeclaration varDecl) {
+ declaredTopLevelVar(varList, varDecl);
+ });
} else if (declaration is ClassTypeAlias) {
declaredClassTypeAlias(declaration);
_visitTypeParameters(declaration, declaration.typeParameters);
@@ -269,10 +263,11 @@
} else if (declaration is GenericTypeAlias) {
declaredGenericTypeAlias(declaration);
_visitTypeParameters(declaration, declaration.typeParameters);
- _visitTypeParameters(
- declaration.functionType,
- declaration.functionType?.typeParameters,
- );
+
+ var type = declaration.type;
+ if (type is GenericFunctionType) {
+ _visitTypeParameters(type, type.typeParameters);
+ }
} else if (declaration is MixinDeclaration) {
declaredMixin(declaration);
_visitTypeParameters(declaration, declaration.typeParameters);
@@ -280,16 +275,16 @@
});
}
- void _visitParamList(FormalParameterList paramList) {
+ void _visitParamList(FormalParameterList? paramList) {
if (paramList != null) {
paramList.parameters.forEach((FormalParameter param) {
- NormalFormalParameter normalParam;
+ NormalFormalParameter? normalParam;
if (param is DefaultFormalParameter) {
normalParam = param.parameter;
} else if (param is NormalFormalParameter) {
normalParam = param;
}
- TypeAnnotation type;
+ TypeAnnotation? type;
if (normalParam is FieldFormalParameter) {
type = normalParam.type;
} else if (normalParam is FunctionTypedFormalParameter) {
@@ -298,7 +293,7 @@
type = normalParam.type;
}
var name = param.identifier;
- declaredParam(name, type);
+ declaredParam(name!, type);
});
}
}
@@ -308,26 +303,21 @@
if (stmt.offset < offset) {
if (stmt is VariableDeclarationStatement) {
var varList = stmt.variables;
- if (varList != null) {
- for (var varDecl in varList.variables) {
- if (varDecl.end < offset) {
- declaredLocalVar(varDecl.name, varList.type);
- }
+ for (var varDecl in varList.variables) {
+ if (varDecl.end < offset) {
+ declaredLocalVar(varDecl.name, varList.type);
}
}
} else if (stmt is FunctionDeclarationStatement) {
var declaration = stmt.functionDeclaration;
- if (declaration != null && declaration.offset < offset) {
- var id = declaration.name;
- if (id != null) {
- var name = id.name;
- if (name != null && name.isNotEmpty) {
- declaredFunction(declaration);
- _visitTypeParameters(
- declaration,
- declaration.functionExpression.typeParameters,
- );
- }
+ if (declaration.offset < offset) {
+ var name = declaration.name.name;
+ if (name.isNotEmpty) {
+ declaredFunction(declaration);
+ _visitTypeParameters(
+ declaration,
+ declaration.functionExpression.typeParameters,
+ );
}
}
}
@@ -335,7 +325,7 @@
}
}
- void _visitTypeParameters(AstNode node, TypeParameterList typeParameters) {
+ void _visitTypeParameters(AstNode node, TypeParameterList? typeParameters) {
if (typeParameters == null) return;
if (node.offset < offset && offset < node.end) {
diff --git a/pkg/analyzer_plugin/lib/utilities/analyzer_converter.dart b/pkg/analyzer_plugin/lib/utilities/analyzer_converter.dart
index 03e3ac4..40f3d2e 100644
--- a/pkg/analyzer_plugin/lib/utilities/analyzer_converter.dart
+++ b/pkg/analyzer_plugin/lib/utilities/analyzer_converter.dart
@@ -23,7 +23,7 @@
/// error's location will have a start line and start column. If a [severity]
/// is provided, then it will override the severity defined by the error.
plugin.AnalysisError convertAnalysisError(analyzer.AnalysisError error,
- {analyzer.LineInfo lineInfo, analyzer.ErrorSeverity severity}) {
+ {analyzer.LineInfo? lineInfo, analyzer.ErrorSeverity? severity}) {
var errorCode = error.errorCode;
severity ??= errorCode.errorSeverity;
var offset = error.offset;
@@ -33,17 +33,13 @@
var endColumn = -1;
if (lineInfo != null) {
var startLocation = lineInfo.getLocation(offset);
- if (startLocation != null) {
- startLine = startLocation.lineNumber;
- startColumn = startLocation.columnNumber;
- }
+ startLine = startLocation.lineNumber;
+ startColumn = startLocation.columnNumber;
var endLocation = lineInfo.getLocation(offset + error.length);
- if (endLocation != null) {
- endLine = endLocation.lineNumber;
- endColumn = endLocation.columnNumber;
- }
+ endLine = endLocation.lineNumber;
+ endColumn = endLocation.columnNumber;
}
- List<plugin.DiagnosticMessage> contextMessages;
+ List<plugin.DiagnosticMessage>? contextMessages;
if (error.contextMessages.isNotEmpty) {
contextMessages = error.contextMessages
.map((message) =>
@@ -69,8 +65,8 @@
/// the errors will be altered based on those options.
List<plugin.AnalysisError> convertAnalysisErrors(
List<analyzer.AnalysisError> errors,
- {analyzer.LineInfo lineInfo,
- analyzer.AnalysisOptions options}) {
+ {analyzer.LineInfo? lineInfo,
+ analyzer.AnalysisOptions? options}) {
var serverErrors = <plugin.AnalysisError>[];
for (var error in errors) {
var processor = analyzer.ErrorProcessor.getProcessor(options, error);
@@ -94,7 +90,7 @@
/// the error's location will have a start line and start column.
plugin.DiagnosticMessage convertDiagnosticMessage(
analyzer.DiagnosticMessage message,
- {analyzer.LineInfo lineInfo}) {
+ {analyzer.LineInfo? lineInfo}) {
var file = message.filePath;
var offset = message.offset;
var length = message.length;
@@ -104,15 +100,11 @@
var endColumn = -1;
if (lineInfo != null) {
var lineLocation = lineInfo.getLocation(offset);
- if (lineLocation != null) {
- startLine = lineLocation.lineNumber;
- startColumn = lineLocation.columnNumber;
- }
+ startLine = lineLocation.lineNumber;
+ startColumn = lineLocation.columnNumber;
var endLocation = lineInfo.getLocation(offset + length);
- if (endLocation != null) {
- endLine = endLocation.lineNumber;
- endColumn = endLocation.columnNumber;
- }
+ endLine = endLocation.lineNumber;
+ endColumn = endLocation.columnNumber;
}
return plugin.DiagnosticMessage(
message.message,
@@ -202,8 +194,8 @@
plugin.AnalysisErrorType(type.name);
/// Create a location based on an the given [element].
- plugin.Location locationFromElement(analyzer.Element element,
- {int offset, int length}) {
+ plugin.Location? locationFromElement(analyzer.Element? element,
+ {int? offset, int? length}) {
if (element == null || element.source == null) {
return null;
}
@@ -234,14 +226,13 @@
// so should it return isEnumConstant = true?
// Or should we return ElementKind.ENUM_CONSTANT here
// in either or both of these cases?
- element.type != null &&
element.type.element == element.enclosingElement) {
return plugin.ElementKind.ENUM_CONSTANT;
}
return convertElementKind(element.kind);
}
- String _getAliasedTypeString(analyzer.Element element) {
+ String? _getAliasedTypeString(analyzer.Element element) {
if (element is analyzer.TypeAliasElement) {
var aliasedType = element.aliasedType;
return aliasedType.getDisplayString(withNullability: false);
@@ -251,7 +242,7 @@
/// Return a textual representation of the parameters of the given [element],
/// or `null` if the element does not have any parameters.
- String _getParametersString(analyzer.Element element) {
+ String? _getParametersString(analyzer.Element element) {
// TODO(scheglov) expose the corresponding feature from ExecutableElement
List<analyzer.ParameterElement> parameters;
if (element is analyzer.ExecutableElement) {
@@ -297,17 +288,14 @@
/// Return a textual representation of the return type of the given [element],
/// or `null` if the element does not have a return type.
- String _getReturnTypeString(analyzer.Element element) {
+ String? _getReturnTypeString(analyzer.Element element) {
if (element is analyzer.ExecutableElement) {
if (element.kind == analyzer.ElementKind.SETTER) {
return null;
}
- return element.returnType?.getDisplayString(withNullability: false);
+ return element.returnType.getDisplayString(withNullability: false);
} else if (element is analyzer.VariableElement) {
- var type = element.type;
- return type != null
- ? type.getDisplayString(withNullability: false)
- : 'dynamic';
+ return element.type.getDisplayString(withNullability: false);
} else if (element is analyzer.TypeAliasElement) {
var aliasedType = element.aliasedType;
if (aliasedType is FunctionType) {
@@ -320,10 +308,10 @@
/// Return a textual representation of the type parameters of the given
/// [element], or `null` if the element does not have type parameters.
- String _getTypeParametersString(analyzer.Element element) {
+ String? _getTypeParametersString(analyzer.Element element) {
if (element is analyzer.TypeParameterizedElement) {
var typeParameters = element.typeParameters;
- if (typeParameters == null || typeParameters.isEmpty) {
+ if (typeParameters.isEmpty) {
return null;
}
return '<${typeParameters.join(', ')}>';
@@ -332,19 +320,22 @@
}
/// Return the compilation unit containing the given [element].
- analyzer.CompilationUnitElement _getUnitElement(analyzer.Element element) {
- if (element is analyzer.CompilationUnitElement) {
- return element;
+ analyzer.CompilationUnitElement? _getUnitElement(analyzer.Element element) {
+ analyzer.Element? currentElement = element;
+ if (currentElement is analyzer.CompilationUnitElement) {
+ return currentElement;
}
- if (element?.enclosingElement is analyzer.LibraryElement) {
- element = element.enclosingElement;
+ if (currentElement.enclosingElement is analyzer.LibraryElement) {
+ currentElement = currentElement.enclosingElement;
}
- if (element is analyzer.LibraryElement) {
- return element.definingCompilationUnit;
+ if (currentElement is analyzer.LibraryElement) {
+ return currentElement.definingCompilationUnit;
}
- for (; element != null; element = element.enclosingElement) {
- if (element is analyzer.CompilationUnitElement) {
- return element;
+ for (;
+ currentElement != null;
+ currentElement = currentElement.enclosingElement) {
+ if (currentElement is analyzer.CompilationUnitElement) {
+ return currentElement;
}
}
return null;
@@ -392,21 +383,24 @@
/// Create and return a location within the given [unitElement] at the given
/// [range].
- plugin.Location _locationForArgs(
- analyzer.CompilationUnitElement unitElement, analyzer.SourceRange range) {
+ plugin.Location? _locationForArgs(
+ analyzer.CompilationUnitElement? unitElement,
+ analyzer.SourceRange range) {
var startLine = 0;
var startColumn = 0;
var endLine = 0;
var endColumn = 0;
+
+ if (unitElement == null) {
+ return null;
+ }
try {
var lineInfo = unitElement.lineInfo;
if (lineInfo != null) {
var offsetLocation = lineInfo.getLocation(range.offset);
startLine = offsetLocation.lineNumber;
startColumn = offsetLocation.columnNumber;
- }
- var endLocation = lineInfo.getLocation(range.offset + range.length);
- if (endLocation != null) {
+ var endLocation = lineInfo.getLocation(range.offset + range.length);
endLine = endLocation.lineNumber;
endColumn = endLocation.columnNumber;
}
diff --git a/pkg/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart b/pkg/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart
index 1546f14..811a510 100644
--- a/pkg/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart
+++ b/pkg/analyzer_plugin/lib/utilities/assist/assist_contributor_mixin.dart
@@ -20,14 +20,13 @@
/// priority, and use the change [builder] to get the edits that comprise the
/// assist. If the message has parameters, then use the list of [args] to
/// populate the message.
- void addAssist(AssistKind kind, ChangeBuilder builder, {List<Object> args}) {
+ void addAssist(AssistKind kind, ChangeBuilder builder, {List<Object>? args}) {
var change = builder.sourceChange;
if (change.edits.isEmpty) {
return;
}
change.id = kind.id;
change.message = formatList(kind.message, args);
- collector.addAssist(
- PrioritizedSourceChange(kind.priority, change));
+ collector.addAssist(PrioritizedSourceChange(kind.priority, change));
}
}
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
index d4e9f29..d64f540 100644
--- a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_core.dart
@@ -23,7 +23,7 @@
/// Return the range of the selection for the change being built, or `null` if
/// there is no selection.
- SourceRange get selectionRange;
+ SourceRange? get selectionRange;
/// Return the source change that was built. The source change will not be
/// complete until all of the futures returned by the add*FileEdit methods
@@ -43,13 +43,6 @@
/// Use the [buildFileEdit] function to create a collection of edits to the
/// file with the given [path]. The edits will be added to the source change
/// that is being built.
- @Deprecated('Use either addDartFileEdit or addGenericFileEdit')
- Future<void> addFileEdit(
- String path, void Function(FileEditBuilder builder) buildFileEdit);
-
- /// Use the [buildFileEdit] function to create a collection of edits to the
- /// file with the given [path]. The edits will be added to the source change
- /// that is being built.
///
/// The builder passed to the [buildFileEdit] function has no special support
/// for any particular kind of file.
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart
index 1b513a2..af9b40a 100644
--- a/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/change_builder_dart.dart
@@ -2,40 +2,16 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
-import 'package:analyzer/dart/analysis/session.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/type_provider.dart';
import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_dart.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
/// The optional generator for prefix that should be used for new imports.
typedef ImportPrefixGenerator = String Function(Uri);
-/// A [ChangeBuilder] used to build changes in Dart files.
-///
-/// Clients may not extend, implement or mix-in this class.
-@Deprecated('Use ChangeBuilder')
-abstract class DartChangeBuilder implements ChangeBuilder {
- /// Initialize a newly created change builder.
- @Deprecated('Use ChangeBuilder(session: session)')
- factory DartChangeBuilder(AnalysisSession session) = DartChangeBuilderImpl;
-
- /// Use the [buildFileEdit] function to create a collection of edits to the
- /// file with the given [path]. The edits will be added to the source change
- /// that is being built.
- ///
- /// If [importPrefixGenerator] is provided, it will be asked to generate an
- /// import prefix for every newly imported library.
- @Deprecated('Use ChangeBuilder.addDartFileEdit')
- @override
- Future<void> addFileEdit(
- String path, void Function(DartFileEditBuilder builder) buildFileEdit,
- {ImportPrefixGenerator importPrefixGenerator});
-}
-
/// An [EditBuilder] used to build edits in Dart files.
///
/// Clients may not extend, implement or mix-in this class.
@@ -55,13 +31,13 @@
/// list of [mixins] is provided but no [superclass] is given then the class
/// will extend `Object`.)
void writeClassDeclaration(String name,
- {Iterable<DartType> interfaces,
+ {Iterable<DartType>? interfaces,
bool isAbstract = false,
- void Function() membersWriter,
- Iterable<DartType> mixins,
- String nameGroupName,
- DartType superclass,
- String superclassGroupName});
+ void Function()? membersWriter,
+ Iterable<DartType>? mixins,
+ String? nameGroupName,
+ DartType? superclass,
+ String? superclassGroupName});
/// Write the code for a constructor declaration in the class with the given
/// [className]. If [isConst] is `true`, then the constructor will be marked
@@ -79,15 +55,15 @@
/// for you). If a [bodyWriter] is provided then it is used to write the
/// constructor body, otherwise an empty body is written.
void writeConstructorDeclaration(String className,
- {ArgumentList argumentList,
- void Function() bodyWriter,
- String classNameGroupName,
- SimpleIdentifier constructorName,
- String constructorNameGroupName,
- List<String> fieldNames,
- void Function() initializerWriter,
+ {ArgumentList? argumentList,
+ void Function()? bodyWriter,
+ String? classNameGroupName,
+ SimpleIdentifier? constructorName,
+ String? constructorNameGroupName,
+ List<String>? fieldNames,
+ void Function()? initializerWriter,
bool isConst = false,
- void Function() parameterWriter});
+ void Function()? parameterWriter});
/// Write the code for a declaration of a field with the given [name]. If an
/// [initializerWriter] is provided, it will be invoked to write the content
@@ -104,13 +80,13 @@
/// required.) If a [typeGroupName] is provided, then if a type was written
/// it will be in the linked edit group with that name.
void writeFieldDeclaration(String name,
- {void Function() initializerWriter,
+ {void Function()? initializerWriter,
bool isConst = false,
bool isFinal = false,
bool isStatic = false,
- String nameGroupName,
- DartType type,
- String typeGroupName});
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName});
/// Write the code for a declaration of a function with the given [name]. If a
/// [bodyWriter] is provided, it will be invoked to write the body of the
@@ -125,12 +101,12 @@
/// declarations of the parameters to the function. (The parentheses around
/// the parameters will automatically be written.)
void writeFunctionDeclaration(String name,
- {void Function() bodyWriter,
+ {void Function()? bodyWriter,
bool isStatic = false,
- String nameGroupName,
- void Function() parameterWriter,
- DartType returnType,
- String returnTypeGroupName});
+ String? nameGroupName,
+ void Function()? parameterWriter,
+ DartType? returnType,
+ String? returnTypeGroupName});
/// Write the code for a declaration of a getter with the given [name]. If a
/// [bodyWriter] is provided, it will be invoked to write the body of the
@@ -166,12 +142,12 @@
/// when required.) If a [typeGroupName] is provided, then if a type was
/// written it will be in the linked edit group with that name.
void writeLocalVariableDeclaration(String name,
- {void Function() initializerWriter,
+ {void Function()? initializerWriter,
bool isConst = false,
bool isFinal = false,
- String nameGroupName,
- DartType type,
- String typeGroupName});
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName});
/// Write the code for a declaration of a mixin with the given [name]. If a
/// list of [interfaces] is provided, then the mixin will implement those
@@ -180,10 +156,10 @@
/// name of the class will be included in the linked edit group with that
/// name.
void writeMixinDeclaration(String name,
- {Iterable<DartType> interfaces,
- void Function() membersWriter,
- String nameGroupName,
- Iterable<DartType> superclassConstraints});
+ {Iterable<DartType>? interfaces,
+ void Function()? membersWriter,
+ String? nameGroupName,
+ Iterable<DartType>? superclassConstraints});
/// Append a placeholder for an override of the specified inherited [element].
/// If provided, write a string value suitable for display (e.g., in a
@@ -191,7 +167,7 @@
/// `true`, then the corresponding `super.name()` will be added in the body.
void writeOverride(
ExecutableElement element, {
- StringBuffer displayTextBuffer,
+ StringBuffer? displayTextBuffer,
bool invokeSuper = false,
});
@@ -218,10 +194,10 @@
void writeParameter(String name,
{bool isCovariant,
bool isRequiredNamed,
- ExecutableElement methodBeingCopied,
- String nameGroupName,
- DartType type,
- String typeGroupName});
+ ExecutableElement? methodBeingCopied,
+ String? nameGroupName,
+ DartType? type,
+ String? typeGroupName});
/// Write the code for a parameter that would match the given [argument]. The
/// name of the parameter will be generated based on the type of the argument,
@@ -238,7 +214,7 @@
/// method are assumed to be part of what is being written and hence valid
/// types.
void writeParameters(Iterable<ParameterElement> parameters,
- {ExecutableElement methodBeingCopied});
+ {ExecutableElement? methodBeingCopied});
/// Write the code for a list of parameters that would match the given list of
/// [arguments]. The surrounding parentheses are *not* written.
@@ -259,11 +235,11 @@
/// parameter. If a [parameterTypeGroupName] is provided, then if a parameter
/// type was written it will be in the linked edit group with that name.
void writeSetterDeclaration(String name,
- {void Function() bodyWriter,
+ {void Function()? bodyWriter,
bool isStatic = false,
- String nameGroupName,
- DartType parameterType,
- String parameterTypeGroupName});
+ String? nameGroupName,
+ DartType? parameterType,
+ String? parameterTypeGroupName});
/// Write the code for a type annotation for the given [type]. If the [type]
/// is either `null` or represents the type 'dynamic', then the behavior
@@ -281,10 +257,10 @@
/// types.
///
/// Return `true` if some text was written.
- bool writeType(DartType type,
+ bool writeType(DartType? type,
{bool addSupertypeProposals = false,
- String groupName,
- ExecutableElement methodBeingCopied,
+ String? groupName,
+ ExecutableElement? methodBeingCopied,
bool required = false});
/// Write the code to declare the given [typeParameter]. The enclosing angle
@@ -294,7 +270,7 @@
/// method are assumed to be part of what is being written and hence valid
/// types.
void writeTypeParameter(TypeParameterElement typeParameter,
- {ExecutableElement methodBeingCopied});
+ {ExecutableElement? methodBeingCopied});
/// Write the code to declare the given list of [typeParameters]. The
/// enclosing angle brackets are automatically written.
@@ -303,12 +279,12 @@
/// method are assumed to be part of what is being written and hence valid
/// types.
void writeTypeParameters(List<TypeParameterElement> typeParameters,
- {ExecutableElement methodBeingCopied});
+ {ExecutableElement? methodBeingCopied});
/// Write the code for a comma-separated list of [types], optionally prefixed
/// by a [prefix]. If the list of [types] is `null` or does not contain any
/// types, then nothing will be written.
- void writeTypes(Iterable<DartType> types, {String prefix});
+ void writeTypes(Iterable<DartType>? types, {String? prefix});
}
/// A [FileEditBuilder] used to build edits for Dart files.
@@ -371,12 +347,12 @@
abstract class DartLinkedEditBuilder implements LinkedEditBuilder {
/// Add the given [type] and all of its supertypes (other than mixins) as
/// suggestions for the current linked edit group.
- void addSuperTypesAsSuggestions(DartType type);
+ void addSuperTypesAsSuggestions(DartType? type);
}
/// Information about a library to import.
abstract class ImportLibraryElementResult {
/// If the library is already imported with a prefix, or should be imported
/// with a prefix, the prefix name (without `.`). Otherwise `null`.
- String get prefix;
+ String? get prefix;
}
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart
index a0f4469..c89a52c 100644
--- a/pkg/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/change_workspace.dart
@@ -7,9 +7,9 @@
/// Information about the workspace in which change builders operate.
abstract class ChangeWorkspace {
/// Return `true` if the file with the given [path] is in a context root.
- bool containsFile(String path);
+ bool? containsFile(String path);
/// Return the session that should analyze the given [path], or throw
/// [StateError] if the [path] does not belong to a context root.
- AnalysisSession getSession(String path);
+ AnalysisSession? getSession(String path);
}
diff --git a/pkg/analyzer_plugin/lib/utilities/change_builder/conflicting_edit_exception.dart b/pkg/analyzer_plugin/lib/utilities/change_builder/conflicting_edit_exception.dart
index db5a55f..624a43f 100644
--- a/pkg/analyzer_plugin/lib/utilities/change_builder/conflicting_edit_exception.dart
+++ b/pkg/analyzer_plugin/lib/utilities/change_builder/conflicting_edit_exception.dart
@@ -3,7 +3,6 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:meta/meta.dart';
/// An exception that is thrown when a change builder is asked to include an
/// edit that conflicts with a previous edit.
@@ -15,8 +14,7 @@
final SourceEdit existingEdit;
/// Initialize a newly created exception indicating that the [newEdit].
- ConflictingEditException(
- {@required this.newEdit, @required this.existingEdit});
+ ConflictingEditException({required this.newEdit, required this.existingEdit});
@override
String toString() =>
diff --git a/pkg/analyzer_plugin/lib/utilities/completion/completion_core.dart b/pkg/analyzer_plugin/lib/utilities/completion/completion_core.dart
index 4c225fe..f12f931 100644
--- a/pkg/analyzer_plugin/lib/utilities/completion/completion_core.dart
+++ b/pkg/analyzer_plugin/lib/utilities/completion/completion_core.dart
@@ -70,7 +70,7 @@
/// Create a 'completion.getSuggestions' response for the file with the given
/// [path]. If any of the contributors throws an exception, also create a
/// non-fatal 'plugin.error' notification.
- Future<GeneratorResult<CompletionGetSuggestionsResult>>
+ Future<GeneratorResult<CompletionGetSuggestionsResult?>>
generateCompletionResponse(CompletionRequest request) async {
var notifications = <Notification>[];
var collector = CompletionCollectorImpl();
@@ -92,7 +92,7 @@
collector.length ??= 0;
var result = CompletionGetSuggestionsResult(
- collector.offset, collector.length, collector.suggestions);
+ collector.offset!, collector.length!, collector.suggestions);
return GeneratorResult(result, notifications);
}
}
diff --git a/pkg/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart b/pkg/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart
index bac46ee..a605f4e 100644
--- a/pkg/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart
+++ b/pkg/analyzer_plugin/lib/utilities/completion/inherited_reference_contributor.dart
@@ -20,13 +20,13 @@
with ElementSuggestionBuilder
implements CompletionContributor {
@override
- LibraryElement containingLibrary;
+ LibraryElement? containingLibrary;
@override
- CompletionSuggestionKind kind;
+ CompletionSuggestionKind? kind;
@override
- ResourceProvider resourceProvider;
+ ResourceProvider? resourceProvider;
/// Plugin contributors should primarily overload this function. Should more
/// parameters be needed for autocompletion needs, the overloaded function
@@ -35,7 +35,7 @@
Future<void> computeSuggestions(
DartCompletionRequest request, CompletionCollector collector) async {
var target =
- CompletionTarget.forOffset(request.result.unit, request.offset);
+ CompletionTarget.forOffset(request.result.unit!, request.offset);
var optype = OpType.forCompletion(target, request.offset);
if (!optype.includeIdentifiers) {
return;
@@ -46,20 +46,20 @@
}
containingLibrary = request.result.libraryElement;
_computeSuggestionsForClass2(
- collector, target, classDecl.declaredElement, optype);
+ collector, target, classDecl.declaredElement!, optype);
}
/// Clients should not overload this function.
Future<void> computeSuggestionsForClass(
DartCompletionRequest request,
CompletionCollector collector,
- ClassElement classElement, {
- AstNode entryPoint,
- bool skipChildClass,
- CompletionTarget target,
- OpType optype,
+ ClassElement? classElement, {
+ AstNode? entryPoint,
+ bool skipChildClass = true,
+ CompletionTarget? target,
+ OpType? optype,
}) async {
- target ??= CompletionTarget.forOffset(request.result.unit, request.offset,
+ target ??= CompletionTarget.forOffset(request.result.unit!, request.offset,
entryPoint: entryPoint);
optype ??= OpType.forCompletion(target, request.offset);
if (!optype.includeIdentifiers) {
@@ -73,7 +73,7 @@
classElement = classDecl.declaredElement;
}
containingLibrary = request.result.libraryElement;
- _computeSuggestionsForClass2(collector, target, classElement, optype,
+ _computeSuggestionsForClass2(collector, target, classElement!, optype,
skipChildClass: skipChildClass);
}
@@ -93,9 +93,7 @@
}
}
for (var elem in type.methods) {
- if (elem.returnType == null) {
- addSuggestion(elem);
- } else if (!elem.returnType.isVoid) {
+ if (!elem.returnType.isVoid) {
if (optype.includeReturnValueSuggestions) {
addSuggestion(elem);
}
@@ -131,8 +129,8 @@
/// Return the class containing the target or `null` if the target is in a
/// static method or field or not in a class.
- ClassDeclaration _enclosingClass(CompletionTarget target) {
- var node = target.containingNode;
+ ClassDeclaration? _enclosingClass(CompletionTarget? target) {
+ var node = target?.containingNode;
while (node != null) {
if (node is ClassDeclaration) {
return node;
diff --git a/pkg/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart b/pkg/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart
index a386ba7..2c8531c 100644
--- a/pkg/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart
+++ b/pkg/analyzer_plugin/lib/utilities/completion/suggestion_builder.dart
@@ -10,8 +10,8 @@
abstract class SuggestionBuilder {
/// Return a suggestion based on the given [element], or `null` if a
/// suggestion is not appropriate for the given element.
- CompletionSuggestion forElement(Element element,
- {String completion,
+ CompletionSuggestion? forElement(Element element,
+ {String? completion,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
int relevance = DART_RELEVANCE_DEFAULT});
}
diff --git a/pkg/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart b/pkg/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart
index 19b3cb0..1009c12 100644
--- a/pkg/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart
+++ b/pkg/analyzer_plugin/lib/utilities/completion/type_member_contributor.dart
@@ -27,11 +27,6 @@
Future<void> computeSuggestions(
DartCompletionRequest request, CompletionCollector collector) async {
var containingLibrary = request.result.libraryElement;
- // Gracefully degrade if the library element is not resolved
- // e.g. detached part file or source change
- if (containingLibrary == null) {
- return;
- }
// Recompute the target since resolution may have changed it
var expression = _computeDotTarget(request, null);
@@ -45,11 +40,6 @@
Future<void> computeSuggestionsWithEntryPoint(DartCompletionRequest request,
CompletionCollector collector, AstNode entryPoint) async {
var containingLibrary = request.result.libraryElement;
- // Gracefully degrade if the library element is not resolved
- // e.g. detached part file or source change
- if (containingLibrary == null) {
- return;
- }
// Recompute the target since resolution may have changed it
var expression = _computeDotTarget(request, entryPoint);
@@ -60,16 +50,20 @@
}
/// Update the completion [target] and [dotTarget] based on the given [unit].
- Expression _computeDotTarget(
- DartCompletionRequest request, AstNode entryPoint) {
- var target = CompletionTarget.forOffset(request.result.unit, request.offset,
+ Expression? _computeDotTarget(
+ DartCompletionRequest request, AstNode? entryPoint) {
+ var target = CompletionTarget.forOffset(
+ request.result.unit!, request.offset,
entryPoint: entryPoint);
var node = target.containingNode;
if (node is MethodInvocation) {
if (identical(node.methodName, target.entity)) {
return node.realTarget;
- } else if (node.isCascaded && node.operator.offset + 1 == target.offset) {
- return node.realTarget;
+ } else if (node.isCascaded) {
+ var operator = node.operator;
+ if (operator != null && operator.offset + 1 == target.offset) {
+ return node.realTarget;
+ }
}
}
if (node is PropertyAccess) {
@@ -129,19 +123,17 @@
}
}
}
- String containingMethodName;
+ String? containingMethodName;
if (expression is SuperExpression && type is InterfaceType) {
// Suggest members from superclass if target is "super"
- type = (type as InterfaceType).superclass;
+ type = type.superclass;
// Determine the name of the containing method because
// the most likely completion is a super expression with same name
var containingMethod =
expression.thisOrAncestorOfType<MethodDeclaration>();
- if (containingMethod != null) {
- var id = containingMethod.name;
- if (id != null) {
- containingMethodName = id.name;
- }
+ var id = containingMethod?.name;
+ if (id != null) {
+ containingMethodName = id.name;
}
}
if (type == null || type.isDynamic) {
@@ -166,7 +158,7 @@
/// The best type for the found declaration,
/// or `null` if no declaration found or failed to determine a type.
- DartType typeFound;
+ DartType? typeFound;
/// Construct a new instance to search for a declaration
_LocalBestTypeVisitor(this.targetName, int offset) : super(offset);
@@ -240,7 +232,7 @@
}
@override
- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) {
+ void declaredLocalVar(SimpleIdentifier name, TypeAnnotation? type) {
if (name.name == targetName) {
var element = name.staticElement as VariableElement;
typeFound = element.type;
@@ -260,7 +252,7 @@
}
@override
- void declaredParam(SimpleIdentifier name, TypeAnnotation type) {
+ void declaredParam(SimpleIdentifier name, TypeAnnotation? type) {
if (name.name == targetName) {
// Type provided by the element in computeFull above
finished();
@@ -330,7 +322,7 @@
/// Create completion suggestions for 'dot' completions on the given [type].
/// If the 'dot' completion is a super expression, then [containingMethodName]
/// is the name of the method in which the completion is requested.
- void buildSuggestions(InterfaceType type, String containingMethodName) {
+ void buildSuggestions(InterfaceType type, String? containingMethodName) {
// Visit all of the types in the class hierarchy, collecting possible
// completions. If multiple elements are found that complete to the same
// identifier, addSuggestion will discard all but the first (with a few
@@ -368,7 +360,7 @@
/// Add a suggestion based upon the given element, provided that it is not
/// shadowed by a previously added suggestion.
- void _addSuggestion(Element element, {int relevance}) {
+ void _addSuggestion(Element element, {int? relevance}) {
if (element.isPrivate) {
if (element.library != containingLibrary) {
// Do not suggest private members for imported libraries
@@ -380,7 +372,7 @@
if (relevance == null) {
// Decrease relevance of suggestions starting with $
// https://github.com/dart-lang/sdk/issues/27303
- if (identifier != null && identifier.startsWith(r'$')) {
+ if (identifier.startsWith(r'$')) {
relevance = DART_RELEVANCE_LOW;
} else {
relevance = DART_RELEVANCE_DEFAULT;
@@ -402,13 +394,15 @@
if ((alreadyGenerated & _COMPLETION_TYPE_GETTER) != 0) {
return;
}
- _completionTypesGenerated[identifier] |= _COMPLETION_TYPE_GETTER;
+ _completionTypesGenerated[identifier] =
+ _completionTypesGenerated[identifier]! | _COMPLETION_TYPE_GETTER;
} else {
// Setters, fields, and methods shadow a setter.
if ((alreadyGenerated & _COMPLETION_TYPE_SETTER) != 0) {
return;
}
- _completionTypesGenerated[identifier] |= _COMPLETION_TYPE_SETTER;
+ _completionTypesGenerated[identifier] =
+ _completionTypesGenerated[identifier]! | _COMPLETION_TYPE_SETTER;
}
} else if (element is FieldElement) {
// Fields and methods shadow a field. A getter/setter pair shadows a
@@ -457,7 +451,7 @@
// in the reverse order.
typesToVisit.addAll(nextType.interfaces);
if (nextType.superclass != null) {
- typesToVisit.add(nextType.superclass);
+ typesToVisit.add(nextType.superclass!);
}
typesToVisit.addAll(nextType.mixins);
}
diff --git a/pkg/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart b/pkg/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart
index b4be5b0..2edbd4c 100644
--- a/pkg/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart
+++ b/pkg/analyzer_plugin/lib/utilities/fixes/fix_contributor_mixin.dart
@@ -15,29 +15,29 @@
/// a mix-in when creating a subclass of [FixContributor].
abstract class FixContributorMixin implements FixContributor {
/// The request that specifies the fixes that are to be built.
- DartFixesRequest request;
+ DartFixesRequest? request;
/// The collector to which fixes should be added.
- FixCollector collector;
+ FixCollector? collector;
/// Add a fix for the given [error]. Use the [kind] of the fix to get the
/// message and priority, and use the change [builder] to get the edits that
/// comprise the fix. If the message has parameters, then use the list of
/// [args] to populate the message.
void addFix(AnalysisError error, FixKind kind, ChangeBuilder builder,
- {List<Object> args}) {
+ {List<Object>? args}) {
var change = builder.sourceChange;
if (change.edits.isEmpty) {
return;
}
change.id = kind.id;
change.message = formatList(kind.message, args);
- collector.addFix(
- error, PrioritizedSourceChange(kind.priority, change));
+ collector?.addFix(error, PrioritizedSourceChange(kind.priority, change));
}
@override
- Future<void> computeFixes(DartFixesRequest request, FixCollector collector) async {
+ Future<void> computeFixes(
+ DartFixesRequest request, FixCollector collector) async {
this.request = request;
this.collector = collector;
try {
diff --git a/pkg/analyzer_plugin/lib/utilities/generator.dart b/pkg/analyzer_plugin/lib/utilities/generator.dart
index 4012c9a..80fabb9 100644
--- a/pkg/analyzer_plugin/lib/utilities/generator.dart
+++ b/pkg/analyzer_plugin/lib/utilities/generator.dart
@@ -9,7 +9,7 @@
/// The result produced by a generator.
///
/// Clients may not extend, implement or mix-in this class.
-class GeneratorResult<T extends ResponseResult> {
+class GeneratorResult<T extends ResponseResult?> {
/// The result to be sent to the server, or `null` if there is no response, as
/// when the generator is generating a notification.
final T result;
diff --git a/pkg/analyzer_plugin/lib/utilities/navigation/navigation.dart b/pkg/analyzer_plugin/lib/utilities/navigation/navigation.dart
index 74d0821..9e02f7a4f 100644
--- a/pkg/analyzer_plugin/lib/utilities/navigation/navigation.dart
+++ b/pkg/analyzer_plugin/lib/utilities/navigation/navigation.dart
@@ -40,7 +40,7 @@
/// should navigate to the given [targetNameLocation].
void addRegion(int offset, int length, ElementKind targetKind,
Location targetNameLocation,
- {Location targetCodeLocation});
+ {Location? targetCodeLocation});
}
/// An object used to produce navigation regions.
@@ -115,7 +115,7 @@
abstract class NavigationRequest {
/// Return the length of the region within the source for which navigation
/// regions are being requested.
- int get length;
+ int? get length;
/// Return the offset of the region within the source for which navigation
/// regions are being requested.
diff --git a/pkg/analyzer_plugin/lib/utilities/navigation/navigation_dart.dart b/pkg/analyzer_plugin/lib/utilities/navigation/navigation_dart.dart
index 4134ed6..dde44ba 100644
--- a/pkg/analyzer_plugin/lib/utilities/navigation/navigation_dart.dart
+++ b/pkg/analyzer_plugin/lib/utilities/navigation/navigation_dart.dart
@@ -18,8 +18,8 @@
ResourceProvider resourceProvider,
NavigationCollector collector,
CompilationUnit unit,
- int offset,
- int length) {
+ int? offset,
+ int? length) {
var dartCollector = _DartNavigationCollector(collector, offset, length);
var visitor = _DartNavigationComputerVisitor(resourceProvider, dartCollector);
if (offset == null || length == null) {
@@ -31,7 +31,7 @@
return collector;
}
-AstNode _getNodeForRange(CompilationUnit unit, int offset, int length) {
+AstNode? _getNodeForRange(CompilationUnit unit, int offset, int length) {
var node = NodeLocator(offset, offset + length).searchWithin(unit);
for (var n = node; n != null; n = n.parent) {
if (n is Directive) {
@@ -44,15 +44,15 @@
/// A Dart specific wrapper around [NavigationCollector].
class _DartNavigationCollector {
final NavigationCollector collector;
- final int requestedOffset;
- final int requestedLength;
+ final int? requestedOffset;
+ final int? requestedLength;
_DartNavigationCollector(
this.collector, this.requestedOffset, this.requestedLength);
- void _addRegion(int offset, int length, Element element) {
+ void _addRegion(int offset, int length, Element? element) {
if (element is FieldFormalParameterElement) {
- element = (element as FieldFormalParameterElement).field;
+ element = element.field;
}
if (element == null || element == DynamicElementImpl.instance) {
return;
@@ -62,8 +62,8 @@
}
// Discard elements that don't span the offset/range given (if provided).
if (requestedOffset != null &&
- (offset > requestedOffset + (requestedLength ?? 0) ||
- offset + length < requestedOffset)) {
+ (offset > requestedOffset! + (requestedLength ?? 0) ||
+ offset + length < requestedOffset!)) {
return;
}
var converter = AnalyzerConverter();
@@ -81,13 +81,13 @@
targetCodeLocation: codeLocation);
}
- void _addRegion_nodeStart_nodeEnd(AstNode a, AstNode b, Element element) {
+ void _addRegion_nodeStart_nodeEnd(AstNode a, AstNode b, Element? element) {
var offset = a.offset;
var length = b.end - offset;
_addRegion(offset, length, element);
}
- void _addRegionForNode(AstNode node, Element element) {
+ void _addRegionForNode(AstNode? node, Element? element) {
if (node == null) {
return;
}
@@ -96,20 +96,20 @@
_addRegion(offset, length, element);
}
- void _addRegionForToken(Token token, Element element) {
+ void _addRegionForToken(Token token, Element? element) {
var offset = token.offset;
var length = token.length;
_addRegion(offset, length, element);
}
/// Get the location of the code (excluding leading doc comments) for this element.
- protocol.Location _getCodeLocation(Element element,
+ protocol.Location? _getCodeLocation(Element element,
protocol.Location location, AnalyzerConverter converter) {
var codeElement = element;
// For synthetic getters created for fields, we need to access the associated
// variable to get the codeOffset/codeLength.
if (codeElement.isSynthetic && codeElement is PropertyAccessorElementImpl) {
- final variable = (codeElement as PropertyAccessorElementImpl).variable;
+ final variable = codeElement.variable;
if (variable is ElementImpl) {
codeElement = variable as ElementImpl;
}
@@ -117,7 +117,7 @@
// Read the main codeOffset from the element. This may include doc comments
// but will give the correct end position.
- int codeOffset, codeLength;
+ int? codeOffset, codeLength;
if (codeElement is ElementImpl) {
codeOffset = codeElement.codeOffset;
codeLength = codeElement.codeLength;
@@ -130,11 +130,13 @@
// Read the declaration so we can get the offset after the doc comments.
// TODO(dantup): Skip this for parts (getParsedLibrary will throw), but find
// a better solution.
- final declaration = !codeElement.session.getFile(location.file).isPart
- ? codeElement.session
- .getParsedLibrary(location.file)
- .getElementDeclaration(codeElement)
- : null;
+ var session = codeElement.session;
+ final declaration =
+ session != null && !session.getFile(location.file).isPart
+ ? session
+ .getParsedLibrary(location.file)
+ .getElementDeclaration(codeElement)
+ : null;
var node = declaration?.node;
if (node is VariableDeclaration) {
node = node.parent;
@@ -147,10 +149,6 @@
codeOffset = offsetAfterDocs;
}
- if (codeOffset == null || codeLength == null) {
- return null;
- }
-
return converter.locationFromElement(element,
offset: codeOffset, length: codeLength);
}
@@ -190,16 +188,16 @@
@override
void visitAssignmentExpression(AssignmentExpression node) {
- node.leftHandSide?.accept(this);
+ node.leftHandSide.accept(this);
computer._addRegionForToken(node.operator, node.staticElement);
- node.rightHandSide?.accept(this);
+ node.rightHandSide.accept(this);
}
@override
void visitBinaryExpression(BinaryExpression node) {
- node.leftOperand?.accept(this);
+ node.leftOperand.accept(this);
computer._addRegionForToken(node.operator, node.staticElement);
- node.rightOperand?.accept(this);
+ node.rightOperand.accept(this);
}
@override
@@ -240,12 +238,10 @@
// associate constructor with "T" or "T.name"
{
AstNode firstNode = node.returnType;
- AstNode lastNode = node.name;
+ AstNode? lastNode = node.name;
lastNode ??= firstNode;
- if (firstNode != null && lastNode != null) {
- computer._addRegion_nodeStart_nodeEnd(
- firstNode, lastNode, node.declaredElement);
- }
+ computer._addRegion_nodeStart_nodeEnd(
+ firstNode, lastNode, node.declaredElement);
}
super.visitConstructorDeclaration(node);
}
@@ -266,7 +262,7 @@
void visitDeclaredIdentifier(DeclaredIdentifier node) {
if (node.type == null) {
var token = node.keyword;
- if (token?.keyword == Keyword.VAR) {
+ if (token != null && token.keyword == Keyword.VAR) {
var inferredType = node.declaredElement?.type;
var element = inferredType?.element;
if (element != null) {
@@ -281,7 +277,7 @@
void visitExportDirective(ExportDirective node) {
var exportElement = node.element;
if (exportElement != null) {
- Element libraryElement = exportElement.exportedLibrary;
+ Element? libraryElement = exportElement.exportedLibrary;
_addUriDirectiveRegion(node, libraryElement);
}
super.visitExportDirective(node);
@@ -291,7 +287,7 @@
void visitImportDirective(ImportDirective node) {
var importElement = node.element;
if (importElement != null) {
- Element libraryElement = importElement.importedLibrary;
+ Element? libraryElement = importElement.importedLibrary;
_addUriDirectiveRegion(node, libraryElement);
}
super.visitImportDirective(node);
@@ -337,7 +333,7 @@
@override
void visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
- Element element = node.staticElement;
+ Element? element = node.staticElement;
if (element != null && element.isSynthetic) {
element = element.enclosingElement;
}
@@ -345,7 +341,7 @@
computer._addRegionForToken(node.thisKeyword, element);
computer._addRegionForNode(node.constructorName, element);
// process arguments
- node.argumentList?.accept(this);
+ node.argumentList.accept(this);
}
@override
@@ -359,7 +355,7 @@
@override
void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
- Element element = node.staticElement;
+ Element? element = node.staticElement;
if (element != null && element.isSynthetic) {
element = element.enclosingElement;
}
@@ -367,7 +363,7 @@
computer._addRegionForToken(node.superKeyword, element);
computer._addRegionForNode(node.constructorName, element);
// process arguments
- node.argumentList?.accept(this);
+ node.argumentList.accept(this);
}
@override
@@ -375,13 +371,13 @@
/// Return the element for the type inferred for each of the variables in
/// the given list of [variables], or `null` if not all variable have the
/// same inferred type.
- Element getCommonElement(List<VariableDeclaration> variables) {
- var firstElement = variables[0].declaredElement.type?.element;
+ Element? getCommonElement(List<VariableDeclaration> variables) {
+ var firstElement = variables[0].declaredElement?.type.element;
if (firstElement == null) {
return null;
}
for (var i = 1; i < variables.length; i++) {
- var element = variables[1].declaredElement.type?.element;
+ var element = variables[1].declaredElement?.type.element;
if (element != firstElement) {
return null;
}
@@ -394,7 +390,7 @@
if (token?.keyword == Keyword.VAR) {
var element = getCommonElement(node.variables);
if (element != null) {
- computer._addRegionForToken(token, element);
+ computer._addRegionForToken(token!, element);
}
}
}
@@ -402,7 +398,7 @@
}
void _addConstructorName(AstNode parent, ConstructorName node) {
- Element element = node.staticElement;
+ Element? element = node.staticElement;
if (element == null) {
return;
}
@@ -435,7 +431,7 @@
/// If the source of the given [element] (referenced by the [node]) exists,
/// then add the navigation region from the [node] to the [element].
- void _addUriDirectiveRegion(UriBasedDirective node, Element element) {
+ void _addUriDirectiveRegion(UriBasedDirective node, Element? element) {
var source = element?.source;
if (source != null) {
if (resourceProvider.getResource(source.fullName).exists) {
diff --git a/pkg/analyzer_plugin/lib/utilities/range_factory.dart b/pkg/analyzer_plugin/lib/utilities/range_factory.dart
index fbcbaa3..b967af5 100644
--- a/pkg/analyzer_plugin/lib/utilities/range_factory.dart
+++ b/pkg/analyzer_plugin/lib/utilities/range_factory.dart
@@ -103,8 +103,8 @@
SourceRange nodeInList<T extends AstNode>(NodeList<T> list, T item) {
if (list.length == 1) {
var nextToken = item.endToken.next;
- if (nextToken.type == TokenType.COMMA) {
- return startEnd(item, nextToken);
+ if (nextToken?.type == TokenType.COMMA) {
+ return startEnd(item, nextToken!);
}
return node(item);
}
diff --git a/pkg/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart b/pkg/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart
index 22b0fec..5022374 100644
--- a/pkg/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart
+++ b/pkg/analyzer_plugin/lib/utilities/subscriptions/subscription_manager.dart
@@ -9,7 +9,7 @@
/// Clients may not extend, implement or mix-in this class.
class SubscriptionManager {
/// The current set of subscriptions.
- Map<AnalysisService, List<String>> _subscriptions;
+ Map<AnalysisService, List<String>>? _subscriptions;
/// Initialize a newly created subscription manager to have no subscriptions.
SubscriptionManager();
@@ -17,10 +17,11 @@
/// Return `true` if the file with the given [filePath] has a subscription for
/// the given [service].
bool hasSubscriptionForFile(String filePath, AnalysisService service) {
- if (_subscriptions == null) {
+ var subscriptions = _subscriptions;
+ if (subscriptions == null) {
return false;
}
- var files = _subscriptions[service];
+ var files = subscriptions[service];
return files != null && files.contains(filePath);
}
@@ -28,8 +29,9 @@
/// has been subscribed.
List<AnalysisService> servicesForFile(String filePath) {
var services = <AnalysisService>[];
- if (_subscriptions != null) {
- _subscriptions.forEach((AnalysisService service, List<String> files) {
+ var subscriptions = _subscriptions;
+ if (subscriptions != null) {
+ subscriptions.forEach((AnalysisService service, List<String> files) {
if (files.contains(filePath)) {
services.add(service);
}
@@ -47,7 +49,8 @@
Map<String, List<AnalysisService>> setSubscriptions(
Map<AnalysisService, List<String>> subscriptions) {
var newSubscriptions = <String, List<AnalysisService>>{};
- if (_subscriptions == null) {
+ var currentSubscriptions = _subscriptions;
+ if (currentSubscriptions == null) {
// This is the first time subscriptions have been set, so all of the
// subscriptions are new.
subscriptions.forEach((AnalysisService service, List<String> paths) {
@@ -61,9 +64,9 @@
// The subscriptions have been changed, to we need to compute the
// difference.
subscriptions.forEach((AnalysisService service, List<String> paths) {
- var oldPaths = _subscriptions[service];
+ var oldPaths = currentSubscriptions[service];
for (var path in paths) {
- if (!oldPaths.contains(path)) {
+ if (oldPaths == null || !oldPaths.contains(path)) {
newSubscriptions
.putIfAbsent(path, () => <AnalysisService>[])
.add(service);
diff --git a/pkg/analyzer_plugin/pubspec.yaml b/pkg/analyzer_plugin/pubspec.yaml
index 2a91465..d2aed483 100644
--- a/pkg/analyzer_plugin/pubspec.yaml
+++ b/pkg/analyzer_plugin/pubspec.yaml
@@ -5,18 +5,18 @@
homepage: https://github.com/dart-lang/sdk/tree/master/pkg/analyzer_plugin
environment:
- sdk: '>=2.9.0 <3.0.0'
+ sdk: '>=2.12.0 <3.0.0'
dependencies:
- analyzer: '>=0.42.0 <0.43.0'
- dart_style: '^1.2.0'
- meta: ^1.2.3
- pub_semver: '^1.3.2'
+ analyzer: ^1.3.0
+ collection: ^1.15.0
+ dart_style: ^2.0.0
+ pub_semver: ^2.0.0
dev_dependencies:
analyzer_utilities:
path: ../analyzer_utilities
- html: '>=0.13.1 <0.15.0'
- path: '^1.4.1'
- test_reflective_loader: ^0.1.8
- test: ^1.0.0
+ html: ^0.15.0
+ path: ^1.8.0
+ test_reflective_loader: ^0.2.0
+ test: ^1.16.6
diff --git a/pkg/analyzer_plugin/test/integration/support/integration_test_methods.dart b/pkg/analyzer_plugin/test/integration/support/integration_test_methods.dart
index 7bc81f3..79c042c 100644
--- a/pkg/analyzer_plugin/test/integration/support/integration_test_methods.dart
+++ b/pkg/analyzer_plugin/test/integration/support/integration_test_methods.dart
@@ -112,10 +112,10 @@
///
/// The stack trace associated with the generation of the error, used for
/// debugging the plugin.
- Stream<PluginErrorParams> onPluginError;
+ late Stream<PluginErrorParams> onPluginError;
/// Stream controller for [onPluginError].
- StreamController<PluginErrorParams> _onPluginError;
+ late StreamController<PluginErrorParams> _onPluginError;
/// Return the navigation information associated with the given region of the
/// given file. If the navigation information for the given file has not yet
@@ -257,7 +257,7 @@
///
/// A table mapping the files whose content has changed to a description of
/// the content change.
- Future sendAnalysisUpdateContent(Map<String, dynamic> files) async {
+ Future sendAnalysisUpdateContent(Map<String, Object> files) async {
var params = AnalysisUpdateContentParams(files).toJson();
var result = await server.send('analysis.updateContent', params);
outOfTestExpect(result, isNull);
@@ -277,10 +277,10 @@
/// errors: List<AnalysisError>
///
/// The errors contained in the file.
- Stream<AnalysisErrorsParams> onAnalysisErrors;
+ late Stream<AnalysisErrorsParams> onAnalysisErrors;
/// Stream controller for [onAnalysisErrors].
- StreamController<AnalysisErrorsParams> _onAnalysisErrors;
+ late StreamController<AnalysisErrorsParams> _onAnalysisErrors;
/// Used to report the folding regions associated with a given file. Folding
/// regions can be nested, but cannot be overlapping. Nesting occurs when a
@@ -304,10 +304,10 @@
/// regions: List<FoldingRegion>
///
/// The folding regions contained in the file.
- Stream<AnalysisFoldingParams> onAnalysisFolding;
+ late Stream<AnalysisFoldingParams> onAnalysisFolding;
/// Stream controller for [onAnalysisFolding].
- StreamController<AnalysisFoldingParams> _onAnalysisFolding;
+ late StreamController<AnalysisFoldingParams> _onAnalysisFolding;
/// Used to report the highlight regions associated with a given file. Each
/// highlight region represents a particular syntactic or semantic meaning
@@ -328,10 +328,10 @@
/// regions: List<HighlightRegion>
///
/// The highlight regions contained in the file.
- Stream<AnalysisHighlightsParams> onAnalysisHighlights;
+ late Stream<AnalysisHighlightsParams> onAnalysisHighlights;
/// Stream controller for [onAnalysisHighlights].
- StreamController<AnalysisHighlightsParams> _onAnalysisHighlights;
+ late StreamController<AnalysisHighlightsParams> _onAnalysisHighlights;
/// Used to report the navigation regions associated with a given file. Each
/// navigation region represents a list of targets associated with some
@@ -369,10 +369,10 @@
///
/// The files containing navigation targets referenced in the file. They
/// are referenced by NavigationTargets by their index in this array.
- Stream<AnalysisNavigationParams> onAnalysisNavigation;
+ late Stream<AnalysisNavigationParams> onAnalysisNavigation;
/// Stream controller for [onAnalysisNavigation].
- StreamController<AnalysisNavigationParams> _onAnalysisNavigation;
+ late StreamController<AnalysisNavigationParams> _onAnalysisNavigation;
/// Used to report the occurrences of references to elements within a single
/// file. None of the occurrence regions should overlap.
@@ -395,10 +395,10 @@
/// occurrences: List<Occurrences>
///
/// The occurrences of references to elements within the file.
- Stream<AnalysisOccurrencesParams> onAnalysisOccurrences;
+ late Stream<AnalysisOccurrencesParams> onAnalysisOccurrences;
/// Stream controller for [onAnalysisOccurrences].
- StreamController<AnalysisOccurrencesParams> _onAnalysisOccurrences;
+ late StreamController<AnalysisOccurrencesParams> _onAnalysisOccurrences;
/// Used to report the outline fragments associated with a single file.
///
@@ -419,10 +419,10 @@
/// outline: List<Outline>
///
/// The outline fragments associated with the file.
- Stream<AnalysisOutlineParams> onAnalysisOutline;
+ late Stream<AnalysisOutlineParams> onAnalysisOutline;
/// Stream controller for [onAnalysisOutline].
- StreamController<AnalysisOutlineParams> _onAnalysisOutline;
+ late StreamController<AnalysisOutlineParams> _onAnalysisOutline;
/// Used to request that completion suggestions for the given offset in the
/// given file be returned.
@@ -642,7 +642,7 @@
/// the refactoring.
Future<EditGetRefactoringResult> sendEditGetRefactoring(RefactoringKind kind,
String file, int offset, int length, bool validateOnly,
- {RefactoringOptions options}) async {
+ {RefactoringOptions? options}) async {
var params = EditGetRefactoringParams(
kind, file, offset, length, validateOnly,
options: options)
@@ -746,7 +746,6 @@
break;
default:
fail('Unexpected notification: $event');
- break;
}
}
}
diff --git a/pkg/analyzer_plugin/test/integration/support/integration_tests.dart b/pkg/analyzer_plugin/test/integration/support/integration_tests.dart
index 3d3391c..0fe14b2 100644
--- a/pkg/analyzer_plugin/test/integration/support/integration_tests.dart
+++ b/pkg/analyzer_plugin/test/integration/support/integration_tests.dart
@@ -39,7 +39,7 @@
/// Assert that [actual] matches [matcher].
void outOfTestExpect(actual, Matcher matcher,
- {String reason, skip, bool verbose = false}) {
+ {String? reason, skip, bool verbose = false}) {
var matchState = {};
try {
if (matcher.matches(actual, matchState)) return;
@@ -50,7 +50,7 @@
}
String _defaultFailFormatter(
- actual, Matcher matcher, String reason, Map matchState, bool verbose) {
+ actual, Matcher matcher, String? reason, Map matchState, bool verbose) {
var description = StringDescription();
description.add('Expected: ').addDescriptionOf(matcher).add('\n');
description.add(' Actual: ').addDescriptionOf(actual).add('\n');
@@ -87,7 +87,7 @@
final Server server = Server();
/// Temporary directory in which source files can be stored.
- Directory sourceDirectory;
+ Directory? sourceDirectory;
/// Map from file path to the list of analysis errors which have most recently
/// been received for the file.
@@ -176,7 +176,7 @@
/// relative to [sourceDirectory]. On Windows any forward slashes in
/// [relativePath] are converted to backslashes.
String sourcePath(String relativePath) {
- return join(sourceDirectory.path, relativePath.replaceAll('/', separator));
+ return join(sourceDirectory!.path, relativePath.replaceAll('/', separator));
}
/// Send the server an 'analysis.setAnalysisRoots' command directing it to
@@ -195,7 +195,7 @@
/// Start [server].
Future startServer(
- {bool checked = true, int diagnosticPort, int servicesPort}) =>
+ {bool checked = true, int? diagnosticPort, int? servicesPort}) =>
server.start(
checked: checked,
diagnosticPort: diagnosticPort,
@@ -204,7 +204,7 @@
/// After every test, the server is stopped and [sourceDirectory] is deleted.
Future tearDown() {
return shutdownIfNeeded().then((_) {
- sourceDirectory.deleteSync(recursive: true);
+ sourceDirectory!.deleteSync(recursive: true);
});
}
@@ -234,28 +234,28 @@
/// The matcher returned by [_creator], if it has already been called.
/// Otherwise null.
- Matcher _wrappedMatcher;
+ Matcher? _wrappedMatcher;
LazyMatcher(this._creator);
@override
Description describe(Description description) {
_createMatcher();
- return _wrappedMatcher.describe(description);
+ return _wrappedMatcher!.describe(description);
}
@override
Description describeMismatch(
item, Description mismatchDescription, Map matchState, bool verbose) {
_createMatcher();
- return _wrappedMatcher.describeMismatch(
- item, mismatchDescription, matchState, verbose);
+ return _wrappedMatcher!
+ .describeMismatch(item, mismatchDescription, matchState, verbose);
}
@override
bool matches(item, Map matchState) {
_createMatcher();
- return _wrappedMatcher.matches(item, matchState);
+ return _wrappedMatcher!.matches(item, matchState);
}
/// Create the wrapped matcher object, if it hasn't been created already.
@@ -292,11 +292,11 @@
/// Fields that are required to be in the JSON object, and [Matcher]s describing
/// their expected types.
- final Map<String, Matcher> requiredFields;
+ final Map<String, Matcher>? requiredFields;
/// Fields that are optional in the JSON object, and [Matcher]s describing
/// their expected types.
- final Map<String, Matcher> optionalFields;
+ final Map<String, Matcher>? optionalFields;
const MatchesJsonObject(this.description, this.requiredFields,
{this.optionalFields});
@@ -311,9 +311,10 @@
mismatches.add(simpleDescription('is not a map'));
return;
}
+ var requiredFields = this.requiredFields;
if (requiredFields != null) {
requiredFields.forEach((String key, Matcher valueMatcher) {
- if (!(item as Map).containsKey(key)) {
+ if (!item.containsKey(key)) {
mismatches.add((Description mismatchDescription) =>
mismatchDescription
.add('is missing field ')
@@ -326,11 +327,12 @@
}
});
}
+ var optionalFields = this.optionalFields;
item.forEach((key, value) {
if (requiredFields != null && requiredFields.containsKey(key)) {
// Already checked this field
} else if (optionalFields != null && optionalFields.containsKey(key)) {
- _checkField(key as String, value, optionalFields[key], mismatches);
+ _checkField(key as String, value, optionalFields[key]!, mismatches);
} else {
mismatches.add((Description mismatchDescription) => mismatchDescription
.add('has unexpected field ')
@@ -357,7 +359,7 @@
/// facilitate communication to and from the server.
class Server {
/// Server process object, or null if server hasn't been started yet.
- Process _process;
+ Process? _process;
/// Commands that have been sent to the server but not yet acknowledged, and
/// the [Completer] objects which should be completed when acknowledgement is
@@ -385,13 +387,13 @@
/// The [currentElapseTime] at which the last communication was received from the server
/// or `null` if no communication has been received.
- double lastCommunicationTime;
+ double? lastCommunicationTime;
/// The current elapse time (seconds) since the server was started.
double get currentElapseTime => _time.elapsedTicks / _time.frequency;
/// Future that completes when the server process exits.
- Future<int> get exitCode => _process.exitCode;
+ Future<int> get exitCode => _process!.exitCode;
/// Print out any messages exchanged with the server. If some messages have
/// already been exchanged with the server, they are printed out immediately.
@@ -421,21 +423,21 @@
/// Return a future that will complete when all commands that have been sent
/// to the server so far have been flushed to the OS buffer.
Future flushCommands() {
- return _process.stdin.flush();
+ return _process!.stdin.flush();
}
/// Stop the server.
Future<int> kill(String reason) {
debugStdio();
_recordStdio('FORCIBLY TERMINATING PROCESS: $reason');
- _process.kill();
- return _process.exitCode;
+ _process!.kill();
+ return _process!.exitCode;
}
/// Start listening to output from the server, and deliver notifications to
/// [notificationProcessor].
void listenToOutput(NotificationProcessor notificationProcessor) {
- _process.stdout
+ _process!.stdout
.transform((Utf8Codec()).decoder)
.transform(LineSplitter())
.listen((String line) {
@@ -485,7 +487,7 @@
outOfTestExpect(message, isNotification);
}
});
- _process.stderr
+ _process!.stderr
.transform((Utf8Codec()).decoder)
.transform(LineSplitter())
.listen((String line) {
@@ -501,7 +503,7 @@
/// normal (non-error) response, the future will be completed with the 'result'
/// field from the response. If the server acknowledges the command with an
/// error response, the future will be completed with an error.
- Future send(String method, Map<String, dynamic> params) {
+ Future send(String method, Map<String, dynamic>? params) {
var id = '${_nextId++}';
var command = <String, dynamic>{'id': id, 'method': method};
if (params != null) {
@@ -511,7 +513,7 @@
_pendingCommands[id] = completer;
var line = json.encode(command);
_recordStdio('SEND: $line');
- _process.stdin.add(utf8.encoder.convert('$line\n'));
+ _process!.stdin.add(utf8.encoder.convert('$line\n'));
return completer.future;
}
@@ -522,10 +524,10 @@
Future start(
{bool checked = true,
bool debugServer = false,
- int diagnosticPort,
+ int? diagnosticPort,
bool profileServer = false,
- String sdkPath,
- int servicesPort,
+ String? sdkPath,
+ int? servicesPort,
bool useAnalysisHighlight2 = false}) {
if (_process != null) {
throw Exception('Process already started');
@@ -782,7 +784,7 @@
@override
Description describeMismatch(
item, Description mismatchDescription, Map matchState, bool verbose) {
- var mismatches = matchState['mismatches'] as List<MismatchDescriber>;
+ var mismatches = matchState['mismatches'] as List<MismatchDescriber>?;
if (mismatches != null) {
for (var i = 0; i < mismatches.length; i++) {
var mismatch = mismatches[i];
diff --git a/pkg/analyzer_plugin/test/plugin/assist_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/assist_mixin_test.dart
index 955290a..4a5899e 100644
--- a/pkg/analyzer_plugin/test/plugin/assist_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/assist_mixin_test.dart
@@ -20,12 +20,12 @@
@reflectiveTest
class AssistsMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
@@ -55,7 +55,8 @@
_TestAssistContributor(this.changes);
@override
- Future<void> computeAssists(AssistRequest request, AssistCollector collector) async {
+ Future<void> computeAssists(
+ AssistRequest request, AssistCollector collector) async {
for (var change in changes) {
collector.addAssist(change);
}
diff --git a/pkg/analyzer_plugin/test/plugin/completion_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/completion_mixin_test.dart
index 36ce569..35ecf19 100644
--- a/pkg/analyzer_plugin/test/plugin/completion_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/completion_mixin_test.dart
@@ -20,12 +20,12 @@
@reflectiveTest
class CompletionMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/fix_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/fix_mixin_test.dart
index 06a1c7f..edb6601 100644
--- a/pkg/analyzer_plugin/test/plugin/fix_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/fix_mixin_test.dart
@@ -24,12 +24,12 @@
@reflectiveTest
class FixesMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
@@ -61,7 +61,8 @@
_TestFixContributor(this.changes);
@override
- Future<void> computeFixes(FixesRequest request, FixCollector collector) async {
+ Future<void> computeFixes(
+ FixesRequest request, FixCollector collector) async {
for (var change in changes) {
collector.addFix(request.errorsToFix[0], change);
}
diff --git a/pkg/analyzer_plugin/test/plugin/folding_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/folding_mixin_test.dart
index 0b2f063..ef7d1cd0 100644
--- a/pkg/analyzer_plugin/test/plugin/folding_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/folding_mixin_test.dart
@@ -23,12 +23,12 @@
@reflectiveTest
class FoldingMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/highlights_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/highlights_mixin_test.dart
index 98e39d5..bbf3d1a 100644
--- a/pkg/analyzer_plugin/test/plugin/highlights_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/highlights_mixin_test.dart
@@ -23,12 +23,12 @@
@reflectiveTest
class HighlightsMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/kythe_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/kythe_mixin_test.dart
index 45588b4..c1df465 100644
--- a/pkg/analyzer_plugin/test/plugin/kythe_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/kythe_mixin_test.dart
@@ -20,12 +20,12 @@
@reflectiveTest
class KytheMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/mocks.dart b/pkg/analyzer_plugin/test/plugin/mocks.dart
index 6d466d2..338593b 100644
--- a/pkg/analyzer_plugin/test/plugin/mocks.dart
+++ b/pkg/analyzer_plugin/test/plugin/mocks.dart
@@ -39,10 +39,10 @@
class MockChannel implements PluginCommunicationChannel {
bool _closed = false;
- void Function() _onDone;
- Function _onError;
- void Function(Notification) _onNotification;
- void Function(Request) _onRequest;
+ void Function()? _onDone;
+ Function? _onError;
+ void Function(Notification)? _onNotification;
+ void Function(Request)? _onRequest;
List<Notification> sentNotifications = <Notification>[];
@@ -56,10 +56,10 @@
}
@override
- void listen(void Function(Request request) onRequest,
- {void Function() onDone,
- Function onError,
- Function(Notification) onNotification}) {
+ void listen(void Function(Request request)? onRequest,
+ {void Function()? onDone,
+ Function? onError,
+ Function(Notification)? onNotification}) {
_onDone = onDone;
_onError = onError;
_onNotification = onNotification;
@@ -67,11 +67,15 @@
}
void sendDone() {
- _onDone();
+ if (_onDone != null) {
+ _onDone!();
+ }
}
void sendError(Object exception, StackTrace stackTrace) {
- _onError(exception, stackTrace);
+ if (_onError != null) {
+ _onError!(exception, stackTrace);
+ }
}
@override
@@ -82,7 +86,7 @@
if (_onNotification == null) {
fail('Unexpected invocation of sendNotification');
}
- _onNotification(notification);
+ _onNotification!(notification);
}
Future<Response> sendRequest(RequestParams params) {
@@ -93,7 +97,7 @@
var request = params.toRequest(id);
var completer = Completer<Response>();
completers[request.id] = completer;
- _onRequest(request);
+ _onRequest!(request);
return completer.future;
}
@@ -103,7 +107,7 @@
throw StateError('Sent a response to a closed channel');
}
var completer = completers.remove(response.id);
- completer.complete(response);
+ completer?.complete(response);
}
}
@@ -117,7 +121,11 @@
@override
final String path;
- MockResolvedUnitResult({this.errors, this.lineInfo, this.path});
+ MockResolvedUnitResult(
+ {List<AnalysisError>? errors, LineInfo? lineInfo, String? path})
+ : errors = errors ?? [],
+ lineInfo = lineInfo ?? LineInfo([0]),
+ path = path ?? '';
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
@@ -149,10 +157,10 @@
class MockSource implements Source {
@override
- TimestampedData<String> get contents => null;
+ TimestampedData<String> get contents => TimestampedData(0, '');
@override
- String get encoding => null;
+ String get encoding => '';
@override
String get fullName => '/pkg/lib/test.dart';
diff --git a/pkg/analyzer_plugin/test/plugin/navigation_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/navigation_mixin_test.dart
index 0fde341..2c3dcfd 100644
--- a/pkg/analyzer_plugin/test/plugin/navigation_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/navigation_mixin_test.dart
@@ -23,12 +23,12 @@
@reflectiveTest
class NavigationMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/occurrences_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/occurrences_mixin_test.dart
index e0159c1..319e1bd 100644
--- a/pkg/analyzer_plugin/test/plugin/occurrences_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/occurrences_mixin_test.dart
@@ -23,12 +23,12 @@
@reflectiveTest
class OccurrencesMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/outline_mixin_test.dart b/pkg/analyzer_plugin/test/plugin/outline_mixin_test.dart
index f3510165..5844fde 100644
--- a/pkg/analyzer_plugin/test/plugin/outline_mixin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/outline_mixin_test.dart
@@ -23,12 +23,12 @@
@reflectiveTest
class OutlineMixinTest with ResourceProviderMixin {
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
void setUp() {
packagePath1 = convertPath('/package1');
diff --git a/pkg/analyzer_plugin/test/plugin/plugin_test.dart b/pkg/analyzer_plugin/test/plugin/plugin_test.dart
index 92d227b..18d77ba 100644
--- a/pkg/analyzer_plugin/test/plugin/plugin_test.dart
+++ b/pkg/analyzer_plugin/test/plugin/plugin_test.dart
@@ -19,16 +19,16 @@
@reflectiveTest
class ServerPluginTest with ResourceProviderMixin {
- MockChannel channel;
- _TestServerPlugin plugin;
+ late MockChannel channel;
+ late _TestServerPlugin plugin;
- String packagePath1;
- String filePath1;
- ContextRoot contextRoot1;
+ late String packagePath1;
+ late String filePath1;
+ late ContextRoot contextRoot1;
- String packagePath2;
- String filePath2;
- ContextRoot contextRoot2;
+ late String packagePath2;
+ late String filePath2;
+ late ContextRoot contextRoot2;
void setUp() {
packagePath1 = convertPath('/package1');
@@ -363,12 +363,12 @@
var notifiedServices = notifications[path];
expect(notifiedServices, isNotNull,
reason: 'Not notified for file $path');
- expect(notifiedServices, unorderedEquals(subscribedServices),
+ expect(notifiedServices, unorderedEquals(subscribedServices!),
reason: 'Wrong notifications for file $path');
}
}
- AnalysisDriverGeneric _getDriver(ContextRoot targetRoot) {
+ AnalysisDriverGeneric? _getDriver(ContextRoot targetRoot) {
for (var root in plugin.driverMap.keys) {
if (root.root == targetRoot.root) {
return plugin.driverMap[root];
diff --git a/pkg/analyzer_plugin/test/src/channel/isolate_channel_test.dart b/pkg/analyzer_plugin/test/src/channel/isolate_channel_test.dart
index 05b5876..d4399d9 100644
--- a/pkg/analyzer_plugin/test/src/channel/isolate_channel_test.dart
+++ b/pkg/analyzer_plugin/test/src/channel/isolate_channel_test.dart
@@ -16,8 +16,8 @@
@reflectiveTest
class PluginIsolateChannelTest {
- TestSendPort sendPort;
- PluginIsolateChannel channel;
+ late TestSendPort sendPort;
+ late PluginIsolateChannel channel;
void setUp() {
sendPort = TestSendPort();
@@ -50,11 +50,11 @@
Future<void> test_listen() async {
var sentRequest = PluginShutdownParams().toRequest('5');
- Request receivedRequest;
+ Request? receivedRequest;
channel.listen((Request request) {
receivedRequest = request;
});
- sendPort.receivePort.send(sentRequest.toJson());
+ sendPort.receivePort?.send(sentRequest.toJson());
await _pumpEventQueue(1);
expect(receivedRequest, sentRequest);
}
@@ -89,7 +89,7 @@
/// A send port used in tests.
class TestSendPort implements SendPort {
/// The receive port used to receive messages from the server.
- SendPort receivePort;
+ SendPort? receivePort;
/// The messages sent to the server.
List<Object> sentMessages = <Object>[];
@@ -103,7 +103,7 @@
fail('Did not receive a receive port as the first communication.');
}
} else {
- sentMessages.add(message);
+ sentMessages.add(message!);
}
}
}
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
index 0e27f7f..4d1c17e 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_core_test.dart
@@ -10,6 +10,8 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
+import 'mocks.dart';
+
void main() {
defineReflectiveSuite(() {
defineReflectiveTests(ChangeBuilderImplTest);
@@ -22,7 +24,7 @@
@reflectiveTest
class ChangeBuilderImplTest {
void test_copy_empty() {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var copy = builder.copy() as ChangeBuilderImpl;
expect(identical(copy, builder), isFalse);
expect(copy.workspace, builder.workspace);
@@ -30,7 +32,7 @@
}
Future<void> test_copy_newEdit() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit('/test.dart', (builder) {
builder.addSimpleInsertion(0, 'x');
});
@@ -43,7 +45,7 @@
}
Future<void> test_copy_newFile() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit('/test1.dart', (builder) {
builder.addSimpleInsertion(0, 'x');
});
@@ -56,7 +58,7 @@
}
Future<void> test_copy_newLinkedEditGroup() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit('/test.dart', (builder) {
builder.addLinkedPosition(SourceRange(1, 2), 'a');
});
@@ -69,7 +71,7 @@
}
Future<void> test_copy_newLinkedPosition() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit('/test.dart', (builder) {
builder.addLinkedPosition(SourceRange(1, 2), 'a');
});
@@ -82,25 +84,16 @@
}
Future<void> test_copy_selection() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
builder.setSelection(Position('/test.dart', 5));
var copy = builder.copy() as ChangeBuilderImpl;
copy.setSelection(Position('/test.dart', 10));
var change = builder.sourceChange;
- expect(change.selection.offset, 5);
- }
-
- Future<void> test_createFileEditBuilder() async {
- var builder = ChangeBuilderImpl();
- var path = '/test.dart';
- var fileEditBuilder = await builder.createGenericFileEditBuilder(path);
- expect(fileEditBuilder, const TypeMatcher<FileEditBuilder>());
- var fileEdit = fileEditBuilder.fileEdit;
- expect(fileEdit.file, path);
+ expect(change.selection!.offset, 5);
}
void test_getLinkedEditGroup() {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var group = builder.getLinkedEditGroup('a');
expect(identical(builder.getLinkedEditGroup('b'), group), isFalse);
expect(identical(builder.getLinkedEditGroup('a'), group), isTrue);
@@ -108,13 +101,13 @@
void test_setSelection() {
var position = Position('test.dart', 3);
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
builder.setSelection(position);
expect(builder.sourceChange.selection, position);
}
void test_sourceChange_emptyEdit() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var path = '/test.dart';
await builder.addGenericFileEdit(path, (builder) {});
var sourceChange = builder.sourceChange;
@@ -126,7 +119,7 @@
}
void test_sourceChange_noEdits() {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var sourceChange = builder.sourceChange;
expect(sourceChange, isNotNull);
expect(sourceChange.edits, isEmpty);
@@ -136,7 +129,7 @@
}
Future<void> test_sourceChange_oneChange() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var path = '/test.dart';
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleInsertion(0, '_');
@@ -156,7 +149,7 @@
String path = '/test.dart';
Future<void> test_addLinkedEdit() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var offset = 10;
var text = 'content';
await builder.addGenericFileEdit(path, (builder) {
@@ -181,7 +174,7 @@
}
Future<void> test_addSimpleLinkedEdit() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var offset = 10;
var text = 'content';
await builder.addGenericFileEdit(path, (builder) {
@@ -204,7 +197,7 @@
}
Future<void> test_createLinkedEditBuilder() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (builder) {
var linkBuilder =
@@ -215,17 +208,17 @@
}
Future<void> test_selectHere() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (EditBuilder builder) {
builder.selectHere();
});
});
- expect(builder.sourceChange.selection.offset, 10);
+ expect(builder.sourceChange.selection!.offset, 10);
}
Future<void> test_write() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var offset = 10;
var text = 'write';
await builder.addGenericFileEdit(path, (builder) {
@@ -253,7 +246,7 @@
}
Future<void> test_writeln_withoutText() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var offset = 52;
var length = 12;
await builder.addGenericFileEdit(path, (builder) {
@@ -281,7 +274,7 @@
}
Future<void> test_writeln_withText() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var offset = 52;
var length = 12;
var text = 'writeln';
@@ -318,7 +311,7 @@
Future<void> test_addDeletion() async {
var offset = 23;
var length = 7;
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addDeletion(SourceRange(offset, length));
});
@@ -337,7 +330,7 @@
var firstLength = 7;
var secondOffset = 30;
var secondLength = 5;
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addDeletion(SourceRange(firstOffset, firstLength));
builder.addDeletion(SourceRange(secondOffset, secondLength));
@@ -360,7 +353,7 @@
var firstLength = 7;
var secondOffset = 30;
var secondLength = 5;
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addDeletion(SourceRange(secondOffset, secondLength));
builder.addDeletion(SourceRange(firstOffset, firstLength));
@@ -382,7 +375,7 @@
var firstLength = 7;
var secondOffset = 27;
var secondLength = 8;
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addDeletion(SourceRange(firstOffset, firstLength));
builder.addDeletion(SourceRange(secondOffset, secondLength));
@@ -395,7 +388,7 @@
}
Future<void> test_addInsertion() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (builder) {
expect(builder, isNotNull);
@@ -404,7 +397,7 @@
}
Future<void> test_addLinkedPosition() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
var groupName = 'a';
await builder.addGenericFileEdit(path, (builder) {
builder.addLinkedPosition(SourceRange(3, 6), groupName);
@@ -420,7 +413,7 @@
}
Future<void> test_addReplacement() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addReplacement(SourceRange(4, 5), (builder) {
expect(builder, isNotNull);
@@ -431,7 +424,7 @@
Future<void> test_addSimpleInsertion() async {
var offset = 23;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleInsertion(offset, text);
});
@@ -445,7 +438,7 @@
Future<void> test_addSimpleInsertion_sameOffset() async {
var offset = 23;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleInsertion(offset, text);
builder.addSimpleInsertion(offset, 'abc');
@@ -464,7 +457,7 @@
var offset = 23;
var length = 7;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleReplacement(SourceRange(offset, length), text);
});
@@ -481,7 +474,7 @@
var secondOffset = firstOffset + firstLength;
var secondLength = 5;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleReplacement(SourceRange(firstOffset, firstLength), text);
builder.addSimpleReplacement(
@@ -501,7 +494,7 @@
var offset = 23;
var length = 7;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleReplacement(SourceRange(offset, length), text);
expect(() {
@@ -519,7 +512,7 @@
var offset = 23;
var length = 7;
var text = 'xyz';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addSimpleReplacement(SourceRange(offset, length), text);
expect(() {
@@ -534,7 +527,7 @@
}
Future<void> test_createEditBuilder() async {
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
var offset = 4;
var length = 5;
@@ -555,7 +548,7 @@
Future<void> test_addSuggestion() async {
var groupName = 'a';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (builder) {
builder.addLinkedEdit(groupName, (builder) {
@@ -571,7 +564,7 @@
Future<void> test_addSuggestion_zeroLength() async {
var groupName = 'a';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (builder) {
builder.addLinkedEdit(groupName, (builder) {
@@ -585,7 +578,7 @@
Future<void> test_addSuggestions() async {
var groupName = 'a';
- var builder = ChangeBuilderImpl();
+ var builder = ChangeBuilderImpl(session: MockAnalysisSession());
await builder.addGenericFileEdit(path, (builder) {
builder.addInsertion(10, (builder) {
builder.addLinkedEdit(groupName, (builder) {
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart
index 430be10..c1f201f 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/change_builder_dart_test.dart
@@ -18,6 +18,7 @@
import '../../../support/abstract_context.dart';
import 'dart/dart_change_builder_mixin.dart';
+import 'mocks.dart';
void main() {
defineReflectiveSuite(() {
@@ -787,9 +788,9 @@
}
class MyClass {}''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
+ var unit = (await resolveFile(path)).unit;
- var A = unit.declarations[1] as ClassDeclaration;
+ var A = unit?.declarations[1] as ClassDeclaration;
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
@@ -799,7 +800,7 @@
initializerWriter: () {
builder.write('null');
},
- type: A.declaredElement.instantiate(
+ type: A.declaredElement?.instantiate(
typeArguments: [],
nullabilitySuffix: NullabilitySuffix.star,
),
@@ -818,16 +819,16 @@
}
class MyClass {}''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
+ var unit = (await resolveFile(path)).unit;
- var A = unit.declarations[1] as ClassDeclaration;
+ var A = unit?.declarations[1] as ClassDeclaration;
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(11, (builder) {
builder.writeLocalVariableDeclaration(
'foo',
- type: A.declaredElement.instantiate(
+ type: A.declaredElement?.instantiate(
typeArguments: [],
nullabilitySuffix: NullabilitySuffix.star,
),
@@ -854,9 +855,9 @@
}
class MyClass {}''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
+ var unit = (await resolveFile(path)).unit;
- var A = unit.declarations[1] as ClassDeclaration;
+ var A = unit?.declarations[1] as ClassDeclaration;
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
@@ -864,7 +865,7 @@
builder.writeLocalVariableDeclaration(
'foo',
isFinal: true,
- type: A.declaredElement.instantiate(
+ type: A.declaredElement?.instantiate(
typeArguments: [],
nullabilitySuffix: NullabilitySuffix.star,
),
@@ -1024,8 +1025,8 @@
class A {}
''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var g = unit.declarations[1] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var g = unit?.declarations[1] as FunctionDeclaration;
var body = g.functionExpression.body as BlockFunctionBody;
var statement = body.block.statements[0] as ExpressionStatement;
var invocation = statement.expression as MethodInvocation;
@@ -1046,15 +1047,15 @@
var content = 'f(int a, {bool b = false, String c}) {}';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var f = unit.declarations[0] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var f = unit?.declarations[0] as FunctionDeclaration;
var parameters = f.functionExpression.parameters;
- var elements = parameters.parameters.map((p) => p.declaredElement);
+ var elements = parameters?.parameters.map((p) => p.declaredElement!);
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 1, (builder) {
- builder.writeParameters(elements);
+ builder.writeParameters(elements!);
});
});
var edit = getEdit(builder);
@@ -1066,15 +1067,15 @@
var path = convertPath('/home/test/lib/test.dart');
var content = 'f(int a, [bool b = false, String c]) {}';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var f = unit.declarations[0] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var f = unit?.declarations[0] as FunctionDeclaration;
var parameters = f.functionExpression.parameters;
- var elements = parameters.parameters.map((p) => p.declaredElement);
+ var elements = parameters?.parameters.map((p) => p.declaredElement!);
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 1, (builder) {
- builder.writeParameters(elements);
+ builder.writeParameters(elements!);
});
});
var edit = getEdit(builder);
@@ -1086,15 +1087,15 @@
var path = convertPath('/home/test/lib/test.dart');
var content = 'f(int i, String s) {}';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var f = unit.declarations[0] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var f = unit?.declarations[0] as FunctionDeclaration;
var parameters = f.functionExpression.parameters;
- var elements = parameters.parameters.map((p) => p.declaredElement);
+ var elements = parameters?.parameters.map((p) => p.declaredElement!);
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 1, (builder) {
- builder.writeParameters(elements);
+ builder.writeParameters(elements!);
});
});
var edit = getEdit(builder);
@@ -1108,8 +1109,8 @@
g(s, index: i);
}''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var f = unit.declarations[0] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var f = unit?.declarations[0] as FunctionDeclaration;
var body = f.functionExpression.body as BlockFunctionBody;
var statement = body.block.statements[0] as ExpressionStatement;
var invocation = statement.expression as MethodInvocation;
@@ -1131,8 +1132,8 @@
g(s, i);
}''';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
- var f = unit.declarations[0] as FunctionDeclaration;
+ var unit = (await resolveFile(path)).unit;
+ var f = unit?.declarations[0] as FunctionDeclaration;
var body = f.functionExpression.body as BlockFunctionBody;
var statement = body.block.statements[0] as ExpressionStatement;
var invocation = statement.expression as MethodInvocation;
@@ -1324,12 +1325,12 @@
var path = convertPath('/home/test/lib/test.dart');
var content = 'class A {}';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
+ var unit = (await resolveFile(path)).unit;
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 1, (builder) {
- var typeProvider = unit.declaredElement.library.typeProvider;
+ var typeProvider = unit!.declaredElement!.library.typeProvider;
builder.writeType(typeProvider.dynamicType);
});
});
@@ -1537,12 +1538,12 @@
var path = convertPath('/home/test/lib/test.dart');
var content = 'class A {}';
addSource(path, content);
- var unit = (await resolveFile(path))?.unit;
+ var unit = (await resolveFile(path)).unit;
var builder = newBuilder();
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 1, (builder) {
- var typeProvider = unit.declaredElement.library.typeProvider;
+ var typeProvider = unit!.declaredElement!.library.typeProvider;
builder.writeType(typeProvider.dynamicType, required: true);
});
});
@@ -1670,7 +1671,7 @@
expect(edit.replacement, equalsIgnoringWhitespace('implements A, B'));
}
- Future<void> _assertWriteType(String typeCode, {String declarations}) async {
+ Future<void> _assertWriteType(String typeCode, {String? declarations}) async {
var path = convertPath('/home/test/lib/test.dart');
var content = (declarations ?? '') + '$typeCode v;';
addSource(path, content);
@@ -1688,14 +1689,14 @@
}
Future<ClassElement> _getClassElement(String path, String name) async {
- var result = (await resolveFile(path))?.unit;
- return result.declaredElement.getType(name);
+ var result = (await resolveFile(path)).unit;
+ return result!.declaredElement!.getType(name)!;
}
Future<PropertyAccessorElement> _getTopLevelAccessorElement(
String path, String name) async {
- var result = (await resolveFile(path))?.unit;
- return result.declaredElement.accessors.firstWhere((v) => v.name == name);
+ var result = (await resolveFile(path)).unit;
+ return result!.declaredElement!.accessors.firstWhere((v) => v.name == name);
}
Future<InterfaceType> _getType(
@@ -1719,7 +1720,7 @@
addSource(path, '''var f = () {}''');
var resolvedUnit = await resolveFile(path);
- var findNode = FindNode(resolvedUnit.content, resolvedUnit.unit);
+ var findNode = FindNode(resolvedUnit.content!, resolvedUnit.unit!);
var body = findNode.functionBody('{}');
var builder = newBuilder();
@@ -1736,7 +1737,7 @@
addSource(path, 'String f() {}');
var resolvedUnit = await resolveFile(path);
- var findNode = FindNode(resolvedUnit.content, resolvedUnit.unit);
+ var findNode = FindNode(resolvedUnit.content!, resolvedUnit.unit!);
var body = findNode.functionBody('{}');
var builder = newBuilder();
@@ -1849,7 +1850,7 @@
addSource(path, 'String f() {}');
var resolvedUnit = await resolveFile(path);
- var findNode = FindNode(resolvedUnit.content, resolvedUnit.unit);
+ var findNode = FindNode(resolvedUnit.content!, resolvedUnit.unit!);
var type = findNode.typeAnnotation('String');
var builder = newBuilder();
@@ -1871,11 +1872,11 @@
class B extends A {}
class C extends B {}
''');
- var unit = (await resolveFile(path))?.unit;
- var classC = unit.declarations[2] as ClassDeclaration;
- var builder = DartLinkedEditBuilderImpl(null);
+ var unit = (await resolveFile(path)).unit;
+ var classC = unit?.declarations[2] as ClassDeclaration;
+ var builder = DartLinkedEditBuilderImpl(MockEditBuilderImpl());
builder.addSuperTypesAsSuggestions(
- classC.declaredElement.instantiate(
+ classC.declaredElement?.instantiate(
typeArguments: [],
nullabilitySuffix: NullabilitySuffix.star,
),
@@ -2328,9 +2329,9 @@
}
Future<void> _assertImportLibrary({
- String initialCode,
- List<String> uriList,
- String expectedCode,
+ required String initialCode,
+ required List<String> uriList,
+ required String expectedCode,
}) async {
var path = convertPath('/home/test/lib/test.dart');
addSource(path, initialCode);
@@ -2878,26 +2879,26 @@
/// given [displayText]. If a [selection] is provided, assert that the
/// generated selection range matches it.
Future<void> _assertWriteOverride({
- String content,
- String nameToOverride,
- String expected,
- String displayText,
- SourceRange selection,
+ required String content,
+ required String nameToOverride,
+ required String expected,
+ String? displayText,
+ SourceRange? selection,
String targetClassName = 'B',
- String targetMixinName,
+ String? targetMixinName,
bool invokeSuper = false,
}) async {
var path = convertPath('/home/test/lib/test.dart');
addSource(path, content);
- ClassElement targetElement;
+ ClassElement? targetElement;
{
- var unitResult = (await resolveFile(path))?.unit;
+ var unitResult = (await resolveFile(path)).unit;
if (targetMixinName != null) {
- targetElement = unitResult.declaredElement.mixins
+ targetElement = unitResult!.declaredElement!.mixins
.firstWhere((e) => e.name == targetMixinName);
} else {
- targetElement = unitResult.declaredElement.types
+ targetElement = unitResult!.declaredElement!.types
.firstWhere((e) => e.name == targetClassName);
}
}
@@ -2913,7 +2914,7 @@
await builder.addDartFileEdit(path, (builder) {
builder.addInsertion(content.length - 2, (builder) {
builder.writeOverride(
- inherited,
+ inherited!,
displayTextBuffer: displayBuffer,
invokeSuper: invokeSuper,
);
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/dart/import_library_element_test.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/dart/import_library_element_test.dart
index 341d53a..84f4e90 100644
--- a/pkg/analyzer_plugin/test/src/utilities/change_builder/dart/import_library_element_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/dart/import_library_element_test.dart
@@ -451,11 +451,11 @@
}
Future<void> _assertImportLibraryElement(
- {String initialCode,
- String uriStr,
- String name,
- String expectedPrefix,
- String expectedCode}) async {
+ {required String initialCode,
+ required String uriStr,
+ required String name,
+ String? expectedPrefix,
+ String? expectedCode}) async {
var offset = initialCode.indexOf('^');
if (offset > 0) {
initialCode =
diff --git a/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart b/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart
new file mode 100644
index 0000000..5d31e68
--- /dev/null
+++ b/pkg/analyzer_plugin/test/src/utilities/change_builder/mocks.dart
@@ -0,0 +1,16 @@
+import 'package:analyzer/dart/analysis/session.dart';
+import 'package:analyzer_plugin/src/utilities/change_builder/change_builder_core.dart';
+
+class MockAnalysisSession implements AnalysisSession {
+ @override
+ dynamic noSuchMethod(Invocation invocation) {
+ return super.noSuchMethod(invocation);
+ }
+}
+
+class MockEditBuilderImpl implements EditBuilderImpl {
+ @override
+ dynamic noSuchMethod(Invocation invocation) {
+ return super.noSuchMethod(invocation);
+ }
+}
diff --git a/pkg/analyzer_plugin/test/src/utilities/completion/completion_target_test.dart b/pkg/analyzer_plugin/test/src/utilities/completion/completion_target_test.dart
index 7a0c3d4..71b649d 100644
--- a/pkg/analyzer_plugin/test/src/utilities/completion/completion_target_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/completion/completion_target_test.dart
@@ -531,7 +531,7 @@
zoo(z) { } String name;''');
assertTarget('/// some dartdoc ', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_FunctionDeclaration_inLineDocComment2() async {
@@ -541,7 +541,7 @@
zoo(z) { } String name;''');
assertTarget('/// some dartdoc', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_FunctionDeclaration_inStarComment() async {
@@ -561,7 +561,7 @@
await createTarget('/** ^ */ zoo(z) { } String name;');
assertTarget('/** */', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_FunctionDeclaration_inStarDocComment2() async {
@@ -569,7 +569,7 @@
await createTarget('/** *^/ zoo(z) { } String name;');
assertTarget('/** */', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_FunctionDeclaration_returnType() async {
@@ -726,7 +726,7 @@
zoo(z) { } String name; }''');
assertTarget('/// some dartdoc ', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_MethodDeclaration_inLineDocComment2() async {
@@ -737,7 +737,7 @@
zoo(z) { } String name; }''');
assertTarget('/// some dartdoc', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_MethodDeclaration_inStarComment() async {
@@ -757,7 +757,7 @@
await createTarget('class C2 {/** ^ */ zoo(z) { } String name; }');
assertTarget('/** */', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_MethodDeclaration_inStarDocComment2() async {
@@ -765,7 +765,7 @@
await createTarget('class C2 {/** *^/ zoo(z) { } String name; }');
assertTarget('/** */', '');
expect(target.containingNode is Comment, isTrue);
- expect(target.containingNode.parent.toSource(), 'zoo(z) {}');
+ expect(target.containingNode.parent!.toSource(), 'zoo(z) {}');
}
Future<void> test_MethodDeclaration_returnType() async {
@@ -885,18 +885,18 @@
}
class _Base extends AbstractContextTest {
- int offset;
- CompletionTarget target;
- FindElement findElement;
+ int? offset;
+ late CompletionTarget target;
+ late FindElement findElement;
void assertTarget(
String entityText,
String nodeText, {
- int argIndex,
- String droppedToken,
+ int? argIndex,
+ String? droppedToken,
bool isFunctionalArgument = false,
- String expectedExecutable,
- String expectedParameter,
+ String? expectedExecutable,
+ String? expectedParameter,
}) {
expect(
target.entity.toString(),
@@ -926,14 +926,14 @@
if (expectedExecutable == null) {
expect(actualExecutable, isNull);
} else {
- expect(_executableStr(actualExecutable), expectedExecutable);
+ expect(_executableStr(actualExecutable!), expectedExecutable);
}
var actualParameter = target.parameterElement;
if (expectedParameter == null) {
expect(actualParameter, isNull);
} else {
- expect(_parameterStr(actualParameter), expectedParameter);
+ expect(_parameterStr(actualParameter!), expectedParameter);
}
expect(target.isFunctionalArgument(), isFunctionalArgument);
@@ -945,18 +945,18 @@
offset = content.indexOf('^');
expect(offset, isNot(equals(-1)), reason: 'missing ^');
- var nextOffset = content.indexOf('^', offset + 1);
+ var nextOffset = content.indexOf('^', offset! + 1);
expect(nextOffset, equals(-1), reason: 'too many ^');
- content = content.substring(0, offset) + content.substring(offset + 1);
+ content = content.substring(0, offset) + content.substring(offset! + 1);
var path = convertPath('/home/test/lib/test.dart');
newFile(path, content: content);
var result = await resolveFile(path);
- findElement = FindElement(result.unit);
+ findElement = FindElement(result.unit!);
- target = CompletionTarget.forOffset(result.unit, offset);
+ target = CompletionTarget.forOffset(result.unit!, offset!);
}
static String _executableNameStr(ExecutableElement executable) {
diff --git a/pkg/analyzer_plugin/test/src/utilities/completion/optype_test.dart b/pkg/analyzer_plugin/test/src/utilities/completion/optype_test.dart
index 57a6f59..66c0b73 100644
--- a/pkg/analyzer_plugin/test/src/utilities/completion/optype_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/completion/optype_test.dart
@@ -18,8 +18,8 @@
/// Common test methods to Dart1/Dart2 versions of OpType tests.
abstract class AbstractOpTypeTest extends AbstractContextTest {
- String testPath;
- int completionOffset;
+ late String testPath;
+ late int completionOffset;
void addTestSource(String content) {
completionOffset = content.indexOf('^');
@@ -33,7 +33,7 @@
Future<void> assertOpType(
{bool caseLabel = false,
- String completionLocation,
+ String? completionLocation,
bool constructors = false,
bool namedArgs = false,
bool prefixed = false,
@@ -50,7 +50,7 @@
//
var resolvedUnit = await resolveFile(testPath);
var completionTarget =
- CompletionTarget.forOffset(resolvedUnit.unit, completionOffset);
+ CompletionTarget.forOffset(resolvedUnit.unit!, completionOffset);
var opType = OpType.forCompletion(completionTarget, completionOffset);
//
// Validate the OpType.
diff --git a/pkg/analyzer_plugin/test/src/utilities/visitors/local_declaration_visitor_test.dart b/pkg/analyzer_plugin/test/src/utilities/visitors/local_declaration_visitor_test.dart
index bf85a20..f06dbb2 100644
--- a/pkg/analyzer_plugin/test/src/utilities/visitors/local_declaration_visitor_test.dart
+++ b/pkg/analyzer_plugin/test/src/utilities/visitors/local_declaration_visitor_test.dart
@@ -42,7 +42,7 @@
TestVisitor(int offset) : super(offset);
@override
- void declaredLocalVar(SimpleIdentifier name, TypeAnnotation type) {
+ void declaredLocalVar(SimpleIdentifier name, TypeAnnotation? type) {
expect(name, isNotNull);
}
}
diff --git a/pkg/analyzer_plugin/test/support/abstract_context.dart b/pkg/analyzer_plugin/test/support/abstract_context.dart
index d9f4ca7..e0776c3 100644
--- a/pkg/analyzer_plugin/test/support/abstract_context.dart
+++ b/pkg/analyzer_plugin/test/support/abstract_context.dart
@@ -19,8 +19,8 @@
import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
/// Finds an [Element] with the given [name].
-Element findChildElement(Element root, String name, [ElementKind kind]) {
- Element result;
+Element? findChildElement(Element root, String name, [ElementKind? kind]) {
+ Element? result;
root.accept(_ElementVisitorFunctionWrapper((Element element) {
if (element.name != name) {
return;
@@ -41,7 +41,7 @@
final Map<String, String> _declaredVariables = {};
- AnalysisContextCollection _analysisContextCollection;
+ AnalysisContextCollection? _analysisContextCollection;
List<String> get collectionIncludedPaths => [workspaceRootPath];
@@ -51,7 +51,7 @@
String get testPackageAnalysisOptionsPath =>
convertPath('$testPackageRootPath/analysis_options.yaml');
- String get testPackageLanguageVersion => '2.9';
+ String? get testPackageLanguageVersion => '2.9';
/// The file system-specific `pubspec.yaml` path.
String get testPackagePubspecPath =>
@@ -69,11 +69,11 @@
_createAnalysisContexts();
path = convertPath(path);
- return _analysisContextCollection.contextFor(path);
+ return _analysisContextCollection!.contextFor(path);
}
/// Create an analysis options file based on the given arguments.
- void createAnalysisOptionsFile({List<String> experiments}) {
+ void createAnalysisOptionsFile({List<String>? experiments}) {
var buffer = StringBuffer();
buffer.writeln('analyzer:');
@@ -116,8 +116,8 @@
}
void writeTestPackageConfig({
- PackageConfigFileBuilder config,
- String languageVersion,
+ PackageConfigFileBuilder? config,
+ String? languageVersion,
bool meta = false,
}) {
if (config == null) {
@@ -163,7 +163,7 @@
mixin WithNonFunctionTypeAliasesMixin on AbstractContextTest {
@override
- String get testPackageLanguageVersion => null;
+ String? get testPackageLanguageVersion => null;
@override
void setUp() {
@@ -179,7 +179,7 @@
mixin WithNullSafetyMixin on AbstractContextTest {
@override
- String get testPackageLanguageVersion => null;
+ String? get testPackageLanguageVersion => null;
}
/// Wraps the given [_ElementVisitorFunction] into an instance of
diff --git a/pkg/analyzer_plugin/test/support/abstract_single_unit.dart b/pkg/analyzer_plugin/test/support/abstract_single_unit.dart
index c46632a..afa5699 100644
--- a/pkg/analyzer_plugin/test/support/abstract_single_unit.dart
+++ b/pkg/analyzer_plugin/test/support/abstract_single_unit.dart
@@ -18,11 +18,11 @@
class AbstractSingleUnitTest extends AbstractContextTest {
bool verifyNoTestUnitErrors = true;
- String testCode;
- String testFile;
- CompilationUnit testUnit;
- FindNode findNode;
- FindElement findElement;
+ late String testCode;
+ late String testFile;
+ late CompilationUnit testUnit;
+ late FindNode findNode;
+ late FindElement findElement;
void addTestSource(String code) {
testCode = code;
@@ -39,7 +39,7 @@
as SimpleIdentifier;
}
- AstNode findNodeAtOffset(int offset, [Predicate<AstNode> predicate]) {
+ AstNode? findNodeAtOffset(int offset, [Predicate<AstNode>? predicate]) {
var result = NodeLocator(offset).searchWithin(testUnit);
if (result != null && predicate != null) {
result = result.thisOrAncestorMatching(predicate);
@@ -47,13 +47,13 @@
return result;
}
- AstNode findNodeAtString(String search, [Predicate<AstNode> predicate]) {
+ AstNode? findNodeAtString(String search, [Predicate<AstNode>? predicate]) {
var offset = findOffset(search);
return findNodeAtOffset(offset, predicate);
}
- Element findNodeElementAtString(String search,
- [Predicate<AstNode> predicate]) {
+ Element? findNodeElementAtString(String search,
+ [Predicate<AstNode>? predicate]) {
var node = findNodeAtString(search, predicate);
if (node == null) {
return null;
@@ -95,8 +95,8 @@
Future<void> resolveTestFile() async {
var result = await resolveFile(testFile);
- testCode = result.content;
- testUnit = result.unit;
+ testCode = result.content!;
+ testUnit = result.unit!;
if (verifyNoTestUnitErrors) {
expect(result.errors.where((AnalysisError error) {
return error.errorCode != HintCode.DEAD_CODE &&
diff --git a/pkg/analyzer_plugin/test/utilities/analyzer_converter_test.dart b/pkg/analyzer_plugin/test/utilities/analyzer_converter_test.dart
index 7acc4203..18c6333 100644
--- a/pkg/analyzer_plugin/test/utilities/analyzer_converter_test.dart
+++ b/pkg/analyzer_plugin/test/utilities/analyzer_converter_test.dart
@@ -38,7 +38,7 @@
expect(element.kind, plugin.ElementKind.METHOD);
expect(element.name, 'myMethod');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 32);
expect(location.length, 'myGetter'.length);
@@ -57,7 +57,7 @@
/// Assert that the given [pluginError] matches the given [analyzerError].
void assertError(
plugin.AnalysisError pluginError, analyzer.AnalysisError analyzerError,
- {analyzer.ErrorSeverity severity,
+ {analyzer.ErrorSeverity? severity,
int startColumn = -1,
int startLine = -1}) {
var errorCode = analyzerError.errorCode;
@@ -77,7 +77,7 @@
expect(pluginError.type, converter.convertErrorType(errorCode.type));
}
- analyzer.AnalysisError createError(int offset, {String contextMessage}) {
+ analyzer.AnalysisError createError(int offset, {String? contextMessage}) {
var contextMessages = <analyzer.DiagnosticMessageImpl>[];
if (contextMessage != null) {
contextMessages.add(analyzer.DiagnosticMessageImpl(
@@ -105,7 +105,7 @@
assertError(pluginError, analyzerError,
startColumn: 4, startLine: 2, severity: severity);
expect(pluginError.contextMessages, hasLength(1));
- var message = pluginError.contextMessages[0];
+ var message = pluginError.contextMessages![0];
expect(message.message, 'here');
expect(message.location.offset, 53);
expect(message.location.length, 7);
@@ -232,7 +232,7 @@
expect(element.name, '_A');
expect(element.typeParameters, isNull);
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 27);
expect(location.length, '_A'.length);
@@ -269,7 +269,7 @@
expect(element.name, 'myConstructor');
expect(element.typeParameters, isNull);
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 20);
expect(location.length, 'myConstructor'.length);
@@ -307,7 +307,7 @@
expect(element.name, '_E1');
expect(element.typeParameters, isNull);
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 17);
expect(location.length, '_E1'.length);
@@ -343,7 +343,7 @@
expect(element.kind, plugin.ElementKind.ENUM_CONSTANT);
expect(element.name, 'one');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 23);
expect(location.length, 'one'.length);
@@ -367,7 +367,7 @@
expect(element.kind, plugin.ElementKind.ENUM_CONSTANT);
expect(element.name, 'three');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 44);
expect(location.length, 'three'.length);
@@ -386,7 +386,7 @@
expect(element.kind, plugin.ElementKind.FIELD);
expect(element.name, 'index');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, -1);
expect(location.length, 'index'.length);
@@ -405,7 +405,7 @@
expect(element.kind, plugin.ElementKind.FIELD);
expect(element.name, 'values');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, -1);
expect(location.length, 'values'.length);
@@ -430,7 +430,7 @@
expect(element.kind, plugin.ElementKind.FIELD);
expect(element.name, 'myField');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 25);
expect(location.length, 'myField'.length);
@@ -454,7 +454,7 @@
expect(element.name, 'F');
expect(element.typeParameters, '<T>');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 12);
expect(location.length, 'F'.length);
@@ -477,7 +477,7 @@
expect(element.kind, plugin.ElementKind.GETTER);
expect(element.name, 'myGetter');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 20);
expect(location.length, 'myGetter'.length);
@@ -503,7 +503,7 @@
expect(element.kind, plugin.ElementKind.LABEL);
expect(element.name, 'myLabel');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 9);
expect(location.length, 'myLabel'.length);
@@ -528,7 +528,7 @@
expect(element.kind, plugin.ElementKind.METHOD);
expect(element.name, 'myMethod');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 32);
expect(location.length, 'myGetter'.length);
@@ -551,7 +551,7 @@
expect(element.kind, plugin.ElementKind.SETTER);
expect(element.name, 'mySetter');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 16);
expect(location.length, 'mySetter'.length);
@@ -574,7 +574,7 @@
expect(element.name, 'F');
expect(element.typeParameters, '<T>');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 8);
expect(location.length, 'F'.length);
@@ -597,7 +597,7 @@
expect(element.name, 'A');
expect(element.typeParameters, '<out T>');
{
- var location = element.location;
+ var location = element.location!;
expect(location.file, testFile);
expect(location.offset, 8);
expect(location.length, 'A'.length);
@@ -665,7 +665,7 @@
class _AnalyzerConverterTest extends AbstractSingleUnitTest {
AnalyzerConverter converter = AnalyzerConverter();
- analyzer.Source source;
+ late analyzer.Source source;
@override
void setUp() {
diff --git a/pkg/analyzer_plugin/test/utilities/completion/completion_contributor_util.dart b/pkg/analyzer_plugin/test/utilities/completion/completion_contributor_util.dart
index 2697933..a7899a0 100644
--- a/pkg/analyzer_plugin/test/utilities/completion/completion_contributor_util.dart
+++ b/pkg/analyzer_plugin/test/utilities/completion/completion_contributor_util.dart
@@ -9,6 +9,7 @@
import 'package:analyzer_plugin/src/utilities/completion/completion_target.dart';
import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
import 'package:analyzer_plugin/utilities/completion/relevance.dart';
+import 'package:collection/collection.dart';
import 'package:test/test.dart';
import '../../support/abstract_context.dart';
@@ -21,13 +22,13 @@
abstract class DartCompletionContributorTest extends AbstractContextTest {
static const String _UNCHECKED = '__UNCHECKED__';
- String testFile;
- int completionOffset;
- int replacementOffset;
- int replacementLength;
- CompletionContributor contributor;
- DartCompletionRequest request;
- List<CompletionSuggestion> suggestions;
+ late String testFile;
+ int? completionOffset;
+ int? replacementOffset;
+ int? replacementLength;
+ late CompletionContributor contributor;
+ DartCompletionRequest? request;
+ List<CompletionSuggestion>? suggestions;
/// If `true` and `null` is specified as the suggestion's expected returnType
/// then the actual suggestion is expected to have a `dynamic` returnType.
@@ -40,10 +41,10 @@
expect(completionOffset, isNull, reason: 'Call addTestUnit exactly once');
completionOffset = content.indexOf('^');
expect(completionOffset, isNot(equals(-1)), reason: 'missing ^');
- var nextOffset = content.indexOf('^', completionOffset + 1);
+ var nextOffset = content.indexOf('^', completionOffset! + 1);
expect(nextOffset, equals(-1), reason: 'too many ^');
content = content.substring(0, completionOffset) +
- content.substring(completionOffset + 1);
+ content.substring(completionOffset! + 1);
addSource(testFile, content);
}
@@ -57,31 +58,31 @@
void assertHasParameterInfo(CompletionSuggestion suggestion) {
expect(suggestion.parameterNames, isNotNull);
expect(suggestion.parameterTypes, isNotNull);
- expect(suggestion.parameterNames.length, suggestion.parameterTypes.length);
+ expect(
+ suggestion.parameterNames!.length, suggestion.parameterTypes!.length);
expect(suggestion.requiredParameterCount,
- lessThanOrEqualTo(suggestion.parameterNames.length));
+ lessThanOrEqualTo(suggestion.parameterNames!.length));
expect(suggestion.hasNamedParameters, isNotNull);
}
- void assertNoSuggestions({CompletionSuggestionKind kind}) {
+ void assertNoSuggestions({CompletionSuggestionKind? kind}) {
if (kind == null) {
- if (suggestions.isNotEmpty) {
+ var suggestions = this.suggestions;
+ if (suggestions != null && suggestions.isNotEmpty) {
failedCompletion('Expected no suggestions', suggestions);
}
return;
}
- var suggestion = suggestions.firstWhere(
- (CompletionSuggestion cs) => cs.kind == kind,
- orElse: () => null);
+ var suggestion = suggestions
+ ?.firstWhereOrNull((CompletionSuggestion cs) => cs.kind == kind);
if (suggestion != null) {
failedCompletion('did not expect completion: $completion\n $suggestion');
}
}
void assertNotSuggested(String completion) {
- var suggestion = suggestions.firstWhere(
- (CompletionSuggestion cs) => cs.completion == completion,
- orElse: () => null);
+ var suggestion = suggestions?.firstWhereOrNull(
+ (CompletionSuggestion cs) => cs.completion == completion);
if (suggestion != null) {
failedCompletion('did not expect completion: $completion\n $suggestion');
}
@@ -90,22 +91,22 @@
CompletionSuggestion assertSuggest(String completion,
{CompletionSuggestionKind csKind = CompletionSuggestionKind.INVOCATION,
int relevance = DART_RELEVANCE_DEFAULT,
- ElementKind elemKind,
+ ElementKind? elemKind,
bool isDeprecated = false,
bool isPotential = false,
- String elemFile,
- int elemOffset,
- int selectionOffset,
- String paramName,
- String paramType,
- String defaultArgListString = _UNCHECKED,
- List<int> defaultArgumentListTextRanges}) {
+ String? elemFile,
+ int? elemOffset,
+ int? selectionOffset,
+ String? paramName,
+ String? paramType,
+ String? defaultArgListString = _UNCHECKED,
+ List<int>? defaultArgumentListTextRanges}) {
var cs =
getSuggest(completion: completion, csKind: csKind, elemKind: elemKind);
if (cs == null) {
failedCompletion('expected $completion $csKind $elemKind', suggestions);
}
- expect(cs.kind, equals(csKind));
+ expect(cs!.kind, equals(csKind));
if (isDeprecated) {
expect(cs.relevance, equals(DART_RELEVANCE_LOW));
} else {
@@ -115,19 +116,20 @@
expect(cs.selectionLength, equals(0));
expect(cs.isDeprecated, equals(isDeprecated));
expect(cs.isPotential, equals(isPotential));
- if (cs.element != null) {
- expect(cs.element.location, isNotNull);
- expect(cs.element.location.file, isNotNull);
- expect(cs.element.location.offset, isNotNull);
- expect(cs.element.location.length, isNotNull);
- expect(cs.element.location.startColumn, isNotNull);
- expect(cs.element.location.startLine, isNotNull);
+ var element = cs.element;
+ if (element != null) {
+ expect(element.location, isNotNull);
+ expect(element.location!.file, isNotNull);
+ expect(element.location!.offset, isNotNull);
+ expect(element.location!.length, isNotNull);
+ expect(element.location!.startColumn, isNotNull);
+ expect(element.location!.startLine, isNotNull);
}
- if (elemFile != null) {
- expect(cs.element.location.file, elemFile);
+ if (element != null && elemFile != null) {
+ expect(element.location!.file, elemFile);
}
- if (elemOffset != null) {
- expect(cs.element.location.offset, elemOffset);
+ if (element != null && elemOffset != null) {
+ expect(element.location!.offset, elemOffset);
}
if (paramName != null) {
expect(cs.parameterName, paramName);
@@ -148,16 +150,16 @@
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
- String elemFile,
- String elemName,
- int elemOffset}) {
+ String? elemFile,
+ String? elemName,
+ int? elemOffset}) {
var cs = assertSuggest(name,
csKind: kind,
relevance: relevance,
isDeprecated: isDeprecated,
elemFile: elemFile,
elemOffset: elemOffset);
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.CLASS));
expect(element.name, equals(elemName ?? name));
@@ -171,7 +173,7 @@
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
var cs = assertSuggest(name, csKind: kind, relevance: relevance);
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.CLASS_TYPE_ALIAS));
expect(element.name, equals(name));
@@ -183,9 +185,9 @@
CompletionSuggestion assertSuggestConstructor(String name,
{int relevance = DART_RELEVANCE_DEFAULT,
- int elemOffset,
+ int? elemOffset,
String defaultArgListString = _UNCHECKED,
- List<int> defaultArgumentListTextRanges}) {
+ List<int>? defaultArgumentListTextRanges}) {
var cs = assertSuggest(name,
relevance: relevance,
elemOffset: elemOffset,
@@ -193,7 +195,7 @@
defaultArgumentListTextRanges: defaultArgumentListTextRanges);
var element = cs.element;
expect(element, isNotNull);
- expect(element.kind, equals(ElementKind.CONSTRUCTOR));
+ expect(element!.kind, equals(ElementKind.CONSTRUCTOR));
var index = name.indexOf('.');
expect(element.name, index >= 0 ? name.substring(index + 1) : '');
return cs;
@@ -203,7 +205,7 @@
{bool isDeprecated = false}) {
var suggestion = assertSuggest(completion, isDeprecated: isDeprecated);
expect(suggestion.isDeprecated, isDeprecated);
- expect(suggestion.element.kind, ElementKind.ENUM);
+ expect(suggestion.element!.kind, ElementKind.ENUM);
return suggestion;
}
@@ -213,11 +215,11 @@
relevance: relevance, isDeprecated: isDeprecated);
expect(suggestion.completion, completion);
expect(suggestion.isDeprecated, isDeprecated);
- expect(suggestion.element.kind, ElementKind.ENUM_CONSTANT);
+ expect(suggestion.element!.kind, ElementKind.ENUM_CONSTANT);
return suggestion;
}
- CompletionSuggestion assertSuggestField(String name, String type,
+ CompletionSuggestion assertSuggestField(String name, String? type,
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false}) {
@@ -228,7 +230,7 @@
isDeprecated: isDeprecated);
// The returnType represents the type of a field
expect(cs.returnType, type ?? 'dynamic');
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.FIELD));
expect(element.name, equals(name));
@@ -239,12 +241,12 @@
return cs;
}
- CompletionSuggestion assertSuggestFunction(String name, String returnType,
+ CompletionSuggestion assertSuggestFunction(String name, String? returnType,
{CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
int relevance = DART_RELEVANCE_DEFAULT,
String defaultArgListString = _UNCHECKED,
- List<int> defaultArgumentListTextRanges}) {
+ List<int>? defaultArgumentListTextRanges}) {
var cs = assertSuggest(name,
csKind: kind,
relevance: relevance,
@@ -256,12 +258,12 @@
} else if (isNullExpectedReturnTypeConsideredDynamic) {
expect(cs.returnType, 'dynamic');
}
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.FUNCTION));
expect(element.name, equals(name));
expect(element.isDeprecated, equals(isDeprecated));
- var param = element.parameters;
+ var param = element.parameters!;
expect(param, isNotNull);
expect(param[0], equals('('));
expect(param[param.length - 1], equals(')'));
@@ -275,7 +277,7 @@
}
CompletionSuggestion assertSuggestFunctionTypeAlias(
- String name, String returnType,
+ String name, String? returnType,
{bool isDeprecated = false,
int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
@@ -288,7 +290,7 @@
} else {
expect(cs.returnType, isNull);
}
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.FUNCTION_TYPE_ALIAS));
expect(element.name, equals(name));
@@ -304,7 +306,7 @@
return cs;
}
- CompletionSuggestion assertSuggestGetter(String name, String returnType,
+ CompletionSuggestion assertSuggestGetter(String name, String? returnType,
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false}) {
@@ -314,7 +316,7 @@
elemKind: ElementKind.GETTER,
isDeprecated: isDeprecated);
expect(cs.returnType, returnType ?? 'dynamic');
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.GETTER));
expect(element.name, equals(name));
@@ -325,12 +327,12 @@
}
CompletionSuggestion assertSuggestMethod(
- String name, String declaringType, String returnType,
+ String name, String declaringType, String? returnType,
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
- String defaultArgListString = _UNCHECKED,
- List<int> defaultArgumentListTextRanges}) {
+ String? defaultArgListString = _UNCHECKED,
+ List<int>? defaultArgumentListTextRanges}) {
var cs = assertSuggest(name,
csKind: kind,
relevance: relevance,
@@ -339,11 +341,11 @@
defaultArgumentListTextRanges: defaultArgumentListTextRanges);
expect(cs.declaringType, equals(declaringType));
expect(cs.returnType, returnType ?? 'dynamic');
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.METHOD));
expect(element.name, equals(name));
- var param = element.parameters;
+ var param = element.parameters!;
expect(param, isNotNull);
expect(param[0], equals('('));
expect(param[param.length - 1], equals(')'));
@@ -369,7 +371,7 @@
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
var cs = assertSuggest(name,
csKind: kind, relevance: relevance, elemKind: ElementKind.SETTER);
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.SETTER));
expect(element.name, equals(name));
@@ -383,7 +385,7 @@
return cs;
}
- CompletionSuggestion assertSuggestTopLevelVar(String name, String returnType,
+ CompletionSuggestion assertSuggestTopLevelVar(String name, String? returnType,
{int relevance = DART_RELEVANCE_DEFAULT,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
var cs = assertSuggest(name, csKind: kind, relevance: relevance);
@@ -392,7 +394,7 @@
} else if (isNullExpectedReturnTypeConsideredDynamic) {
expect(cs.returnType, 'dynamic');
}
- var element = cs.element;
+ var element = cs.element!;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.TOP_LEVEL_VARIABLE));
expect(element.name, equals(name));
@@ -413,17 +415,17 @@
Future computeSuggestions() async {
var result = await resolveFile(testFile);
request =
- DartCompletionRequestImpl(resourceProvider, completionOffset, result);
+ DartCompletionRequestImpl(resourceProvider, completionOffset!, result);
var target =
- CompletionTarget.forOffset(request.result.unit, request.offset);
- var range = target.computeReplacementRange(request.offset);
+ CompletionTarget.forOffset(request!.result.unit!, request!.offset);
+ var range = target.computeReplacementRange(request!.offset);
replacementOffset = range.offset;
replacementLength = range.length;
// Request completions
var collector = CompletionCollectorImpl();
- await contributor.computeSuggestions(request, collector);
+ await contributor.computeSuggestions(request!, collector);
suggestions = collector.suggestions;
expect(suggestions, isNotNull, reason: 'expected suggestions');
}
@@ -431,7 +433,7 @@
CompletionContributor createContributor();
void failedCompletion(String message,
- [Iterable<CompletionSuggestion> completions]) {
+ [Iterable<CompletionSuggestion>? completions]) {
var sb = StringBuffer(message);
if (completions != null) {
sb.write('\n found');
@@ -444,13 +446,13 @@
fail(sb.toString());
}
- CompletionSuggestion getSuggest(
- {String completion,
- CompletionSuggestionKind csKind,
- ElementKind elemKind}) {
- CompletionSuggestion cs;
+ CompletionSuggestion? getSuggest(
+ {String? completion,
+ CompletionSuggestionKind? csKind,
+ ElementKind? elemKind}) {
+ CompletionSuggestion? cs;
if (suggestions != null) {
- suggestions.forEach((CompletionSuggestion s) {
+ suggestions?.forEach((CompletionSuggestion s) {
if (completion != null && completion != s.completion) {
return;
}
@@ -467,7 +469,7 @@
cs = s;
} else {
failedCompletion('expected exactly one $cs',
- suggestions.where((s) => s.completion == completion));
+ suggestions!.where((s) => s.completion == completion));
}
});
}
diff --git a/pkg/analyzer_plugin/test/utilities/completion/inherited_reference_contributor_test.dart b/pkg/analyzer_plugin/test/utilities/completion/inherited_reference_contributor_test.dart
index 2b63605..9ee63f3 100644
--- a/pkg/analyzer_plugin/test/utilities/completion/inherited_reference_contributor_test.dart
+++ b/pkg/analyzer_plugin/test/utilities/completion/inherited_reference_contributor_test.dart
@@ -200,10 +200,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, true);
}
@@ -220,10 +220,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, true);
}
@@ -243,10 +243,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, false);
}
@@ -264,10 +264,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, false);
}
@@ -287,10 +287,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, true);
}
@@ -307,10 +307,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, true);
}
@@ -367,10 +367,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, false);
}
@@ -387,10 +387,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, false);
}
@@ -410,10 +410,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'A', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 2);
expect(suggestion.hasNamedParameters, false);
}
diff --git a/pkg/analyzer_plugin/test/utilities/completion/type_member_contributor_test.dart b/pkg/analyzer_plugin/test/utilities/completion/type_member_contributor_test.dart
index 59a19c1..4f20366 100644
--- a/pkg/analyzer_plugin/test/utilities/completion/type_member_contributor_test.dart
+++ b/pkg/analyzer_plugin/test/utilities/completion/type_member_contributor_test.dart
@@ -39,13 +39,13 @@
''');
await computeSuggestions();
var suggestionsForX = suggestions
- .where((CompletionSuggestion s) => s.completion == 'x')
+ ?.where((CompletionSuggestion s) => s.completion == 'x')
.toList();
expect(suggestionsForX, hasLength(1));
if (shouldBeShadowed) {
- expect(suggestionsForX[0].declaringType, 'Derived');
+ expect(suggestionsForX![0].declaringType, 'Derived');
} else {
- expect(suggestionsForX[0].declaringType, 'Base');
+ expect(suggestionsForX![0].declaringType, 'Base');
}
}
@@ -428,7 +428,7 @@
int a;
int^ b = 1;}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 3);
+ expect(replacementOffset, completionOffset! - 3);
expect(replacementLength, 3);
assertNotSuggested('A');
assertNotSuggested('int');
@@ -451,7 +451,7 @@
i^
b = 1;}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('A');
assertNotSuggested('int');
@@ -934,7 +934,7 @@
class Z { }''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('X');
@@ -1075,7 +1075,7 @@
void b() { }}
class Z { }''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('partT8');
assertNotSuggested('partBoo');
@@ -1090,7 +1090,7 @@
'/proj/testAB.dart', 'import "package:myBar/bar.dart"; class Foo { }');
addTestSource('class C {foo(){F^}}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('Foo');
// TODO(danrubel) implement
@@ -1197,7 +1197,7 @@
class X{}
main() {A a; a^..b}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('b');
assertNotSuggested('_c');
@@ -1324,7 +1324,7 @@
class _B {}
A Sew;''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('A');
assertNotSuggested('_B');
@@ -1580,7 +1580,7 @@
addTestSource('''
main() {new String.fr^omCharCodes([]);}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 2);
+ expect(replacementOffset, completionOffset! - 2);
expect(replacementLength, 13);
// Suggested by NamedConstructorContributor
assertNotSuggested('fromCharCodes');
@@ -1837,7 +1837,7 @@
// DeclaredIdentifier ForEachStatement Block
addTestSource('main(args) {for (S^ foo in args) {}}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('args');
assertNotSuggested('foo');
@@ -1875,7 +1875,7 @@
// SimpleIdentifier ForStatement
addTestSource('main() {for (int index = 0; i^)}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('index');
}
@@ -1895,7 +1895,7 @@
// SimpleIdentifier ForStatement
addTestSource('main() {for (int index = 0; index < 10; i^)}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('index');
}
@@ -1906,7 +1906,7 @@
void bar() { }
main() {for (int index = 0; index < 10; ++i^)}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('index');
assertNotSuggested('main');
@@ -2054,9 +2054,9 @@
''');
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'int');
- expect(suggestion.parameterTypes[0], 'int');
- expect(suggestion.element.returnType, 'int');
- expect(suggestion.element.parameters, '(int t)');
+ expect(suggestion.parameterTypes![0], 'int');
+ expect(suggestion.element!.returnType, 'int');
+ expect(suggestion.element!.parameters, '(int t)');
}
Future<void> test_generic_setter() async {
@@ -2073,7 +2073,7 @@
// as a parmeter to it, and it will check the appropriate field in
// the suggestion object.
var suggestion = assertSuggestSetter('t');
- expect(suggestion.element.parameters, '(int value)');
+ expect(suggestion.element!.parameters, '(int value)');
}
Future<void> test_genericTypeAlias_noFunctionType() async {
@@ -2227,7 +2227,7 @@
addSource('/testAB.dart', 'class Foo { }');
addTestSource('class C {foo(){new F^}}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('Future');
assertNotSuggested('Foo');
@@ -2386,7 +2386,7 @@
class A {int x; int y() => 0;}
main(){var a; if (a is Obj^)}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 3);
+ expect(replacementOffset, completionOffset! - 3);
expect(replacementLength, 3);
assertNotSuggested('a');
assertNotSuggested('main');
@@ -2414,7 +2414,7 @@
var m;
main() {new^ X.c();}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 3);
+ expect(replacementOffset, completionOffset! - 3);
expect(replacementLength, 3);
assertNotSuggested('c');
assertNotSuggested('_d');
@@ -2561,7 +2561,7 @@
class C2 { }
foo = {T^''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('T2');
}
@@ -2581,7 +2581,7 @@
class C2 { }
foo = {7:T^};''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('T2');
}
@@ -2595,10 +2595,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, true);
}
@@ -2612,10 +2612,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 1);
expect(suggestion.hasNamedParameters, false);
}
@@ -2629,10 +2629,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, true);
}
@@ -2660,10 +2660,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 0);
expect(suggestion.hasNamedParameters, false);
}
@@ -2677,10 +2677,10 @@
await computeSuggestions();
var suggestion = assertSuggestMethod('m', 'C', 'void');
expect(suggestion.parameterNames, hasLength(2));
- expect(suggestion.parameterNames[0], 'x');
- expect(suggestion.parameterTypes[0], 'dynamic');
- expect(suggestion.parameterNames[1], 'y');
- expect(suggestion.parameterTypes[1], 'int');
+ expect(suggestion.parameterNames![0], 'x');
+ expect(suggestion.parameterTypes![0], 'dynamic');
+ expect(suggestion.parameterNames![1], 'y');
+ expect(suggestion.parameterTypes![1], 'int');
expect(suggestion.requiredParameterCount, 2);
expect(suggestion.hasNamedParameters, false);
}
@@ -3347,7 +3347,7 @@
import "a.dart";
class X {foo(){A^.bar}}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('A');
assertNotSuggested('X');
@@ -3465,7 +3465,7 @@
// SimpleIdentifier MethodInvocation PropertyAccess ExpressionStatement
addTestSource('class A {a() {"hello".to^String().length}}');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 2);
+ expect(replacementOffset, completionOffset! - 2);
expect(replacementLength, 8);
assertSuggestGetter('length', 'int');
assertNotSuggested('A');
@@ -3798,7 +3798,7 @@
m(X x) {} I _n(X x) {}}
class X{}''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
// Contributed by FieldFormalConstructorContributor
assertNotSuggested('b');
@@ -3946,7 +3946,7 @@
class C<E> {}
main() { C<C^> c; }''');
await computeSuggestions();
- expect(replacementOffset, completionOffset - 1);
+ expect(replacementOffset, completionOffset! - 1);
expect(replacementLength, 1);
assertNotSuggested('C1');
assertNotSuggested('C2');
diff --git a/pkg/analyzer_plugin/test/verify_tests_test.dart b/pkg/analyzer_plugin/test/verify_tests_test.dart
index 48657ce..f7414bb 100644
--- a/pkg/analyzer_plugin/test/verify_tests_test.dart
+++ b/pkg/analyzer_plugin/test/verify_tests_test.dart
@@ -16,7 +16,7 @@
}
class _VerifyTests extends VerifyTests {
- _VerifyTests(String testDirPath, {List<String> excludedPaths})
+ _VerifyTests(String testDirPath, {List<String>? excludedPaths})
: super(testDirPath, excludedPaths: excludedPaths);
@override
diff --git a/pkg/analyzer_plugin/tool/spec/api.dart b/pkg/analyzer_plugin/tool/spec/api.dart
index 6b4508a..04ef8d8 100644
--- a/pkg/analyzer_plugin/tool/spec/api.dart
+++ b/pkg/analyzer_plugin/tool/spec/api.dart
@@ -13,11 +13,11 @@
final String version;
final List<Domain> domains;
final Types types;
- final Refactorings refactorings;
+ final Refactorings? refactorings;
Api(this.version, this.domains, this.types, this.refactorings,
dom.Element html,
- {bool experimental})
+ {bool? experimental})
: super(html, experimental, false);
}
@@ -30,9 +30,9 @@
final bool deprecated;
/// Html element representing this part of the API.
- final dom.Element html;
+ final dom.Element? html;
- ApiNode(this.html, bool experimental, bool deprecated)
+ ApiNode(this.html, bool? experimental, bool? deprecated)
: experimental = experimental ?? false,
deprecated = deprecated ?? false;
}
@@ -57,7 +57,7 @@
final List<Notification> notifications;
Domain(this.name, this.requests, this.notifications, dom.Element html,
- {bool experimental, bool deprecated})
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
}
@@ -73,9 +73,9 @@
///
/// If it is not possible (because the chain ends with a [TypeReference] that
/// is not defined in the API), then that final [TypeReference] is returned.
- TypeDecl resolveTypeReferenceChain(TypeDecl type) {
+ TypeDecl? resolveTypeReferenceChain(TypeDecl? type) {
while (type is TypeReference && api.types.containsKey(type.typeName)) {
- type = api.types[(type as TypeReference).typeName].type;
+ type = api.types[type.typeName]?.type;
}
return type;
}
@@ -93,29 +93,29 @@
void visitNotification(Notification notification) {
if (notification.params != null) {
- visitTypeDecl(notification.params);
+ visitTypeDecl(notification.params!);
}
}
void visitRefactoring(Refactoring refactoring) {
if (refactoring.feedback != null) {
- visitTypeDecl(refactoring.feedback);
+ visitTypeDecl(refactoring.feedback!);
}
if (refactoring.options != null) {
- visitTypeDecl(refactoring.options);
+ visitTypeDecl(refactoring.options!);
}
}
- void visitRefactorings(Refactorings refactorings) {
+ void visitRefactorings(Refactorings? refactorings) {
refactorings?.forEach(visitRefactoring);
}
void visitRequest(Request request) {
if (request.params != null) {
- visitTypeDecl(request.params);
+ visitTypeDecl(request.params!);
}
if (request.result != null) {
- visitTypeDecl(request.result);
+ visitTypeDecl(request.result!);
}
}
@@ -173,10 +173,10 @@
/// Type of the object associated with the "params" key in the notification
/// object, or null if the notification has no parameters.
- final TypeObject params;
+ final TypeObject? params;
Notification(this.domainName, this.event, this.params, dom.Element html,
- {bool experimental})
+ {bool? experimental})
: super(html, experimental, false);
/// Get the name of the notification, including the domain prefix.
@@ -190,7 +190,7 @@
value: '$domainName.$event')
];
if (params != null) {
- fields.add(TypeObjectField('params', params, null));
+ fields.add(TypeObjectField('params', params!, null));
}
return TypeObject(fields, null);
}
@@ -204,14 +204,14 @@
/// Type of the refactoring feedback, or null if the refactoring has no
/// feedback.
- final TypeObject feedback;
+ final TypeObject? feedback;
/// Type of the refactoring options, or null if the refactoring has no
/// options.
- final TypeObject options;
+ final TypeObject? options;
Refactoring(this.kind, this.feedback, this.options, dom.Element html,
- {bool experimental})
+ {bool? experimental})
: super(html, experimental, false);
}
@@ -219,7 +219,7 @@
class Refactorings extends ApiNode with IterableMixin<Refactoring> {
final List<Refactoring> refactorings;
- Refactorings(this.refactorings, dom.Element html, {bool experimental})
+ Refactorings(this.refactorings, dom.Element html, {bool? experimental})
: super(html, experimental, false);
@override
@@ -236,15 +236,15 @@
/// Type of the object associated with the "params" key in the request object,
/// or null if the request has no parameters.
- final TypeObject params;
+ final TypeObject? params;
/// Type of the object associated with the "result" key in the response
/// object, or null if the response has no results.
- final TypeObject result;
+ final TypeObject? result;
Request(
this.domainName, this.method, this.params, this.result, dom.Element html,
- {bool experimental, bool deprecated})
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
/// Get the name of the request, including the domain prefix.
@@ -259,7 +259,7 @@
value: '$domainName.$method')
];
if (params != null) {
- fields.add(TypeObjectField('params', params, null));
+ fields.add(TypeObjectField('params', params!, null));
}
return TypeObject(fields, null);
}
@@ -273,7 +273,7 @@
optional: true)
];
if (result != null) {
- fields.add(TypeObjectField('result', result, null));
+ fields.add(TypeObjectField('result', result!, null));
}
return TypeObject(fields, null);
}
@@ -281,7 +281,7 @@
/// Base class for all possible types.
abstract class TypeDecl extends ApiNode {
- TypeDecl(dom.Element html, bool experimental, bool deprecated)
+ TypeDecl(dom.Element? html, bool? experimental, bool? deprecated)
: super(html, experimental, deprecated);
T accept<T>(ApiVisitor<T> visitor);
@@ -295,7 +295,7 @@
bool isExternal = false;
TypeDefinition(this.name, this.type, dom.Element html,
- {bool experimental, bool deprecated})
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
}
@@ -304,7 +304,8 @@
class TypeEnum extends TypeDecl {
final List<TypeEnumValue> values;
- TypeEnum(this.values, dom.Element html, {bool experimental, bool deprecated})
+ TypeEnum(this.values, dom.Element html,
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
@override
@@ -316,7 +317,7 @@
final String value;
TypeEnumValue(this.value, dom.Element html,
- {bool experimental, bool deprecated})
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
}
@@ -324,7 +325,7 @@
class TypeList extends TypeDecl {
final TypeDecl itemType;
- TypeList(this.itemType, dom.Element html, {bool experimental})
+ TypeList(this.itemType, dom.Element html, {bool? experimental})
: super(html, experimental, false);
@override
@@ -342,7 +343,7 @@
/// Type of map values.
final TypeDecl valueType;
- TypeMap(this.keyType, this.valueType, dom.Element html, {bool experimental})
+ TypeMap(this.keyType, this.valueType, dom.Element html, {bool? experimental})
: super(html, experimental, false);
@override
@@ -353,15 +354,15 @@
class TypeObject extends TypeDecl {
final List<TypeObjectField> fields;
- TypeObject(this.fields, dom.Element html,
- {bool experimental, bool deprecated})
+ TypeObject(this.fields, dom.Element? html,
+ {bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
@override
T accept<T>(ApiVisitor<T> visitor) => visitor.visitTypeObject(this);
/// Return the field with the given [name], or null if there is no such field.
- TypeObjectField getField(String name) {
+ TypeObjectField? getField(String name) {
for (var field in fields) {
if (field.name == name) {
return field;
@@ -378,10 +379,10 @@
final bool optional;
/// Value that the field is required to contain, or null if it may vary.
- final Object value;
+ final Object? value;
- TypeObjectField(this.name, this.type, dom.Element html,
- {this.optional = false, this.value, bool experimental, bool deprecated})
+ TypeObjectField(this.name, this.type, dom.Element? html,
+ {this.optional = false, this.value, bool? experimental, bool? deprecated})
: super(html, experimental, deprecated);
}
@@ -390,7 +391,7 @@
class TypeReference extends TypeDecl {
final String typeName;
- TypeReference(this.typeName, dom.Element html, {bool experimental})
+ TypeReference(this.typeName, dom.Element? html, {bool? experimental})
: super(html, experimental, false) {
if (typeName.isEmpty) {
throw Exception('Empty type name');
@@ -407,7 +408,7 @@
List<String> importUris = <String>[];
- Types(this.types, dom.Element html, {bool experimental})
+ Types(this.types, dom.Element html, {bool? experimental})
: super(html, experimental, false);
@override
@@ -415,7 +416,7 @@
Iterable<String> get keys => types.keys;
- TypeDefinition operator [](String typeName) => types[typeName];
+ TypeDefinition? operator [](String typeName) => types[typeName];
bool containsKey(String typeName) => types.containsKey(typeName);
}
@@ -427,7 +428,7 @@
/// The field that is used to disambiguate this union
final String field;
- TypeUnion(this.choices, this.field, dom.Element html, {bool experimental})
+ TypeUnion(this.choices, this.field, dom.Element html, {bool? experimental})
: super(html, experimental, false);
@override
diff --git a/pkg/analyzer_plugin/tool/spec/codegen_dart.dart b/pkg/analyzer_plugin/tool/spec/codegen_dart.dart
index 9dacf99..d0d03f1 100644
--- a/pkg/analyzer_plugin/tool/spec/codegen_dart.dart
+++ b/pkg/analyzer_plugin/tool/spec/codegen_dart.dart
@@ -20,7 +20,7 @@
var typeName = type.typeName;
var referencedDefinition = api.types[typeName];
if (_typeRenames.containsKey(typeName)) {
- return _typeRenames[typeName];
+ return _typeRenames[typeName]!;
}
if (referencedDefinition == null) {
return typeName;
@@ -35,9 +35,15 @@
} else if (type is TypeMap) {
return 'Map<${dartType(type.keyType)}, ${dartType(type.valueType)}>';
} else if (type is TypeUnion) {
- return 'dynamic';
+ return 'Object';
} else {
throw Exception("Can't convert to a dart type");
}
}
+
+ /// Return the Dart type for [field], nullable if the field is optional.
+ String fieldDartType(TypeObjectField field) {
+ var typeStr = dartType(field.type);
+ return field.optional ? '$typeStr?' : typeStr;
+ }
}
diff --git a/pkg/analyzer_plugin/tool/spec/codegen_dart_protocol.dart b/pkg/analyzer_plugin/tool/spec/codegen_dart_protocol.dart
index 6497fe8..99ab0c3 100644
--- a/pkg/analyzer_plugin/tool/spec/codegen_dart_protocol.dart
+++ b/pkg/analyzer_plugin/tool/spec/codegen_dart_protocol.dart
@@ -243,7 +243,7 @@
/// Emit the toJson() code for an empty class.
void emitEmptyToJsonMember() {
writeln('@override');
- writeln('Map<String, dynamic> toJson() => <String, dynamic>{};');
+ writeln('Map<String, Object> toJson() => <String, Object>{};');
}
/// Emit a class to encapsulate an enum.
@@ -253,7 +253,7 @@
toHtmlVisitor.write(impliedType.humanReadableName);
});
if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
+ toHtmlVisitor.showType(null, impliedType.type!);
}
toHtmlVisitor.p(() {
toHtmlVisitor.write(disclaimer);
@@ -342,7 +342,7 @@
void emitEnumFromJsonConstructor(
String className, TypeEnum type, ImpliedType impliedType) {
writeln(
- 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object json) {');
+ 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object? json) {');
indent(() {
writeln('if (json is String) {');
indent(() {
@@ -387,7 +387,7 @@
toHtmlVisitor.write(impliedType.humanReadableName);
});
if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
+ toHtmlVisitor.showType(null, impliedType.type!);
}
toHtmlVisitor.p(() {
toHtmlVisitor.write(disclaimer);
@@ -413,7 +413,20 @@
if (field.value != null) {
continue;
}
- writeln('${dartType(field.type)} _${field.name};');
+
+ // if (!field.optional) {
+ // write('late ');
+ // }
+ // write(dartType(field.type));
+ // if (field.optional) {
+ // write('?');
+ // }
+ // write(' _${field.name};');
+
+ var lateStr = field.optional ? '' : 'late';
+ var questionStr = field.optional ? '?' : '';
+ writeln('$lateStr ${dartType(field.type)}$questionStr _${field.name};');
+
writeln();
}
for (var field in type.fields) {
@@ -423,16 +436,13 @@
docComment(toHtmlVisitor.collectHtml(() {
toHtmlVisitor.translateHtml(field.html);
}));
- writeln('${dartType(field.type)} get ${field.name} => _${field.name};');
+ writeln('${fieldDartType(field)} get ${field.name} => _${field.name};');
writeln();
docComment(toHtmlVisitor.collectHtml(() {
toHtmlVisitor.translateHtml(field.html);
}));
- writeln('set ${field.name}(${dartType(field.type)} value) {');
+ writeln('set ${field.name}(${fieldDartType(field)} value) {');
indent(() {
- if (!field.optional) {
- writeln('assert(value != null);');
- }
writeln('_${field.name} = value;');
});
writeln('}');
@@ -484,9 +494,9 @@
if (field.value != null) {
continue;
}
- var arg = '${dartType(field.type)} ${field.name}';
var setValueFromArg = 'this.${field.name} = ${field.name};';
if (isOptionalConstructorArg(className, field)) {
+ var arg = '${dartType(field.type)}? ${field.name}';
optionalArgs.add(arg);
if (!field.optional) {
// Optional constructor arg, but non-optional field. If no arg is
@@ -514,6 +524,7 @@
});
}
} else {
+ var arg = '${dartType(field.type)} ${field.name}';
args.add(arg);
extraInitCode.add(() {
writeln(setValueFromArg);
@@ -538,7 +549,7 @@
}
/// Emit the operator== code for an object class.
- void emitObjectEqualsMember(TypeObject type, String className) {
+ void emitObjectEqualsMember(TypeObject? type, String className) {
writeln('@override');
writeln('bool operator ==(other) {');
indent(() {
@@ -573,7 +584,7 @@
var humanReadableNameString = literalString(impliedType.humanReadableName);
if (className == 'RefactoringFeedback') {
writeln('factory RefactoringFeedback.fromJson(JsonDecoder jsonDecoder, '
- 'String jsonPath, Object json, Map responseJson) {');
+ 'String jsonPath, Object? json, Map responseJson) {');
indent(() {
writeln('return refactoringFeedbackFromJson(jsonDecoder, jsonPath, '
'json, responseJson);');
@@ -583,7 +594,7 @@
}
if (className == 'RefactoringOptions') {
writeln('factory RefactoringOptions.fromJson(JsonDecoder jsonDecoder, '
- 'String jsonPath, Object json, RefactoringKind kind) {');
+ 'String jsonPath, Object? json, RefactoringKind kind) {');
indent(() {
writeln('return refactoringOptionsFromJson(jsonDecoder, jsonPath, '
'json, kind);');
@@ -592,7 +603,7 @@
return;
}
writeln(
- 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object json) {');
+ 'factory $className.fromJson(JsonDecoder jsonDecoder, String jsonPath, Object? json) {');
indent(() {
writeln('json ??= {};');
writeln('if (json is Map) {');
@@ -618,11 +629,11 @@
} else {
args.add(field.name);
}
- var fieldType = field.type;
- var fieldDartType = dartType(fieldType);
- writeln('$fieldDartType ${field.name};');
+ var typeStr = fieldDartType(field);
+ writeln('$typeStr ${field.name};');
writeln('if (json.containsKey($fieldNameString)) {');
indent(() {
+ var fieldType = field.type;
var fromJson =
fromJsonCode(fieldType).asSnippet(jsonPath, fieldAccessor);
writeln('${field.name} = $fromJson;');
@@ -653,7 +664,7 @@
}
/// Emit the hashCode getter for an object class.
- void emitObjectHashCode(TypeObject type, String className) {
+ void emitObjectHashCode(TypeObject? type, String className) {
writeln('@override');
writeln('int get hashCode {');
indent(() {
@@ -691,7 +702,7 @@
'Returns the [RefactoringProblemSeverity] with the maximal severity.')
]);
writeln(
- 'static RefactoringProblemSeverity max(RefactoringProblemSeverity a, RefactoringProblemSeverity b) =>');
+ 'static RefactoringProblemSeverity? max(RefactoringProblemSeverity? a, RefactoringProblemSeverity? b) =>');
writeln(' maxRefactoringProblemSeverity(a, b);');
return true;
default:
@@ -762,7 +773,7 @@
docComment([
dom.Text('Returns the [FileEdit] for the given [file], maybe `null`.')
]);
- writeln('SourceFileEdit getFileEdit(String file) =>');
+ writeln('SourceFileEdit? getFileEdit(String file) =>');
writeln(' getChangeFileEdit(this, file);');
return true;
case 'SourceEdit':
@@ -826,9 +837,9 @@
/// Emit the toJson() code for an object class.
void emitToJsonMember(TypeObject type) {
writeln('@override');
- writeln('Map<String, dynamic> toJson() {');
+ writeln('Map<String, Object> toJson() {');
indent(() {
- writeln('var result = <String, dynamic>{};');
+ writeln('var result = <String, Object>{};');
for (var field in type.fields) {
var fieldNameString = literalString(field.name);
if (field.value != null) {
@@ -839,7 +850,9 @@
var fieldToJson = toJsonCode(field.type).asSnippet(field.name);
var populateField = 'result[$fieldNameString] = $fieldToJson;';
if (field.optional) {
- writeln('if (${field.name} != null) {');
+ var name = field.name;
+ writeln('var $name = this.$name;');
+ writeln('if ($name != null) {');
indent(() {
writeln(populateField);
});
@@ -1083,7 +1096,10 @@
throw Exception('Union types must be unions of objects');
}
}
- return ToJsonSnippet(dartType(type), (String value) => '$value.toJson()');
+ return ToJsonSnippet(
+ dartType(type),
+ (String value) => '($value as dynamic).toJson()',
+ );
} else if (resolvedType is TypeObject || resolvedType is TypeEnum) {
return ToJsonSnippet(dartType(type), (String value) => '$value.toJson()');
} else {
@@ -1148,7 +1164,7 @@
@override
String get asClosure =>
- '(String jsonPath, Object json) => ${callback('jsonPath', 'json')}';
+ '(String jsonPath, Object? json) => ${callback('jsonPath', 'json')}';
@override
bool get isIdentity => false;
diff --git a/pkg/analyzer_plugin/tool/spec/codegen_inttest_methods.dart b/pkg/analyzer_plugin/tool/spec/codegen_inttest_methods.dart
index fe65490..0a44cfc 100644
--- a/pkg/analyzer_plugin/tool/spec/codegen_inttest_methods.dart
+++ b/pkg/analyzer_plugin/tool/spec/codegen_inttest_methods.dart
@@ -47,11 +47,11 @@
/// Generate a function argument for the given parameter field.
String formatArgument(TypeObjectField field) =>
- '${dartType(field.type)} ${field.name}';
+ '${fieldDartType(field)} ${field.name}';
/// Figure out the appropriate Dart type for data having the given API
/// protocol [type].
- String jsonType(TypeDecl type) {
+ String jsonType(TypeDecl? type) {
type = resolveTypeReferenceChain(type);
if (type is TypeEnum) {
return 'String';
@@ -130,7 +130,6 @@
writeln('default:');
indent(() {
writeln("fail('Unexpected notification: \$event');");
- writeln('break;');
});
});
writeln('}');
@@ -152,12 +151,12 @@
toHtmlVisitor.translateHtml(notification.html);
toHtmlVisitor.describePayload(notification.params, 'Parameters');
}));
- writeln('Stream<$className> $streamName;');
+ writeln('late Stream<$className> $streamName;');
writeln();
docComment(toHtmlVisitor.collectHtml(() {
toHtmlVisitor.write('Stream controller for [$streamName].');
}));
- writeln('StreamController<$className> _$streamName;');
+ writeln('late StreamController<$className> _$streamName;');
fieldInitializationCode.add(collectCode(() {
writeln('_$streamName = StreamController<$className>(sync: true);');
writeln('$streamName = _$streamName.stream.asBroadcastStream();');
@@ -185,8 +184,9 @@
var methodName = camelJoin(['send', request.domainName, request.method]);
var args = <String>[];
var optionalArgs = <String>[];
- if (request.params != null) {
- for (var field in request.params.fields) {
+ var params = request.params;
+ if (params != null) {
+ for (var field in params.fields) {
if (field.optional) {
optionalArgs.add(formatArgument(field));
} else {
@@ -206,8 +206,8 @@
if (request.deprecated) {
writeln('@deprecated');
}
- String resultClass;
- String futureClass;
+ String? resultClass;
+ String? futureClass;
if (request.result == null) {
futureClass = 'Future';
} else {
@@ -221,11 +221,12 @@
[request.domainName, request.method, 'params'],
doCapitalize: true);
var paramsVar = 'null';
- if (request.params != null) {
+ var params = request.params;
+ if (params != null) {
paramsVar = 'params';
var args = <String>[];
var optionalArgs = <String>[];
- for (var field in request.params.fields) {
+ for (var field in params.fields) {
if (field.optional) {
optionalArgs.add('${field.name}: ${field.name}');
} else {
diff --git a/pkg/analyzer_plugin/tool/spec/codegen_matchers.dart b/pkg/analyzer_plugin/tool/spec/codegen_matchers.dart
index 9e3e2fd..f9a7d27 100644
--- a/pkg/analyzer_plugin/tool/spec/codegen_matchers.dart
+++ b/pkg/analyzer_plugin/tool/spec/codegen_matchers.dart
@@ -22,7 +22,7 @@
/// Short human-readable string describing the context of the matcher being
/// created.
- String context;
+ String? context;
CodegenMatchersVisitor(Api api)
: toHtmlVisitor = ToHtmlVisitor(api),
@@ -41,17 +41,19 @@
context = impliedType.humanReadableName;
docComment(toHtmlVisitor.collectHtml(() {
toHtmlVisitor.p(() {
- toHtmlVisitor.write(context);
+ toHtmlVisitor.write(context!);
});
- if (impliedType.type != null) {
- toHtmlVisitor.showType(null, impliedType.type);
+ var type = impliedType.type;
+ if (type != null) {
+ toHtmlVisitor.showType(null, type);
}
}));
write('final Matcher ${camelJoin(['is', impliedType.camelName])} = ');
- if (impliedType.type == null) {
+ var type = impliedType.type;
+ if (type == null) {
write('isNull');
} else {
- visitTypeDecl(impliedType.type);
+ visitTypeDecl(type);
}
writeln(';');
writeln();
diff --git a/pkg/analyzer_plugin/tool/spec/codegen_protocol_constants.dart b/pkg/analyzer_plugin/tool/spec/codegen_protocol_constants.dart
index 52618ac..648859a 100644
--- a/pkg/analyzer_plugin/tool/spec/codegen_protocol_constants.dart
+++ b/pkg/analyzer_plugin/tool/spec/codegen_protocol_constants.dart
@@ -99,7 +99,7 @@
/// Generate a constant for each of the fields in the given [type], where the
/// name of each constant will be composed from the [parentName] and the name
/// of the field.
- void _addFieldConstants(String parentName, TypeObject type) {
+ void _addFieldConstants(String parentName, TypeObject? type) {
if (type == null) {
return;
}
diff --git a/pkg/analyzer_plugin/tool/spec/from_html.dart b/pkg/analyzer_plugin/tool/spec/from_html.dart
index 977737b..cd144a9 100644
--- a/pkg/analyzer_plugin/tool/spec/from_html.dart
+++ b/pkg/analyzer_plugin/tool/spec/from_html.dart
@@ -75,8 +75,8 @@
Api api;
var versions = <String>[];
var domains = <Domain>[];
- Types types;
- Refactorings refactorings;
+ Types? types;
+ Refactorings? refactorings;
recurse(html, 'api', {
'domain': (dom.Element element) {
domains.add(domainFromHtml(element));
@@ -97,7 +97,7 @@
if (versions.length != 1) {
throw Exception('The API must contain exactly one <version> element');
}
- api = Api(versions[0], domains, types, refactorings, html);
+ api = Api(versions[0], domains, types!, refactorings, html);
return api;
}
@@ -125,7 +125,7 @@
}
/// Check that the given [element] has the given [expectedName].
- void checkName(dom.Element element, String expectedName, [String context]) {
+ void checkName(dom.Element element, String expectedName, [String? context]) {
if (element.localName != expectedName) {
context ??= element.localName;
throw Exception(
@@ -158,7 +158,7 @@
notifications.add(notificationFromHtml(child, context));
}
});
- return Domain(name, requests, notifications, html,
+ return Domain(name!, requests, notifications, html,
experimental: experimental);
}
@@ -186,18 +186,18 @@
///
/// Child elements can occur in any order.
Notification notificationFromHtml(dom.Element html, String context) {
- var domainName = getAncestor(html, 'domain', context).attributes['name'];
+ var domainName = getAncestor(html, 'domain', context).attributes['name']!;
checkName(html, 'notification', context);
var event = html.attributes['event'];
context = '$context.${event ?? 'event'}';
checkAttributes(html, ['event'], context);
- TypeObject params;
+ late TypeObject params;
recurse(html, context, {
'params': (dom.Element child) {
params = typeObjectFromHtml(child, '$context.params');
}
});
- return Notification(domainName, event, params, html);
+ return Notification(domainName, event!, params, html);
}
/// Create a single of [TypeDecl] corresponding to the type defined inside the
@@ -249,8 +249,8 @@
},
'map': (dom.Element child) {
checkAttributes(child, [], context);
- TypeDecl keyType;
- TypeDecl valueType;
+ TypeDecl? keyType;
+ TypeDecl? valueType;
recurse(child, context, {
'key': (dom.Element child) {
if (keyType != null) {
@@ -271,7 +271,7 @@
if (valueType == null) {
throw Exception('$context: Value type not specified');
}
- types.add(TypeMap(keyType as TypeReference, valueType, child));
+ types.add(TypeMap(keyType as TypeReference, valueType!, child));
},
'enum': (dom.Element child) {
types.add(typeEnumFromHtml(child, context));
@@ -284,7 +284,7 @@
checkAttributes(child, ['field'], context);
var field = child.attributes['field'];
types.add(
- TypeUnion(processContentsAsTypes(child, context), field, child));
+ TypeUnion(processContentsAsTypes(child, context), field!, child));
}
});
return types;
@@ -295,7 +295,7 @@
var htmlContents = File(filePath).readAsStringSync();
var document = parser.parse(htmlContents);
var htmlElement = document.children
- .singleWhere((element) => element.localName.toLowerCase() == 'html');
+ .singleWhere((element) => element.localName?.toLowerCase() == 'html');
return apiFromHtml(htmlElement);
}
@@ -309,7 +309,7 @@
for (var node in parent.nodes) {
if (node is dom.Element) {
if (elementProcessors.containsKey(node.localName)) {
- elementProcessors[node.localName](node);
+ elementProcessors[node.localName]!(node);
} else if (specialElements.contains(node.localName)) {
throw Exception('$context: Unexpected use of <${node.localName}>');
} else {
@@ -335,8 +335,8 @@
var kind = html.attributes['kind'];
var context = kind ?? 'refactoring';
checkAttributes(html, ['kind'], context);
- TypeObject feedback;
- TypeObject options;
+ TypeObject? feedback;
+ TypeObject? options;
recurse(html, context, {
'feedback': (dom.Element child) {
feedback = typeObjectFromHtml(child, '$context.feedback');
@@ -345,7 +345,7 @@
options = typeObjectFromHtml(child, '$context.options');
}
});
- return Refactoring(kind, feedback, options, html);
+ return Refactoring(kind!, feedback, options, html);
}
/// Create a [Refactorings] object from an HTML representation such as:
@@ -380,7 +380,7 @@
///
/// Child elements can occur in any order.
Request requestFromHtml(dom.Element html, String context) {
- var domainName = getAncestor(html, 'domain', context).attributes['name'];
+ var domainName = getAncestor(html, 'domain', context).attributes['name']!;
checkName(html, 'request', context);
var method = html.attributes['method'];
context = '$context.${method ?? 'method'}';
@@ -388,8 +388,8 @@
optionalAttributes: ['experimental', 'deprecated']);
var experimental = html.attributes['experimental'] == 'true';
var deprecated = html.attributes['deprecated'] == 'true';
- TypeObject params;
- TypeObject result;
+ TypeObject? params;
+ TypeObject? result;
recurse(html, context, {
'params': (dom.Element child) {
params = typeObjectFromHtml(child, '$context.params');
@@ -398,7 +398,7 @@
result = typeObjectFromHtml(child, '$context.result');
}
});
- return Request(domainName, method, params, result, html,
+ return Request(domainName, method!, params, result, html,
experimental: experimental, deprecated: deprecated);
}
@@ -420,7 +420,7 @@
var type = processContentsAsType(html, context);
var experimental = html.attributes['experimental'] == 'true';
var deprecated = html.attributes['deprecated'] == 'true';
- return TypeDefinition(name, type, html,
+ return TypeDefinition(name!, type, html,
experimental: experimental, deprecated: deprecated);
}
@@ -500,7 +500,7 @@
}
var value = html.attributes['value'];
var type = processContentsAsType(html, context);
- return TypeObjectField(name, type, html,
+ return TypeObjectField(name!, type, html,
optional: optional, value: value, deprecated: deprecated);
}
@@ -541,7 +541,7 @@
var api = reader.readApi();
for (var typeDefinition in api.types) {
typeDefinition.isExternal = true;
- childElements.add(typeDefinition.html);
+ childElements.add(typeDefinition.html!);
typeMap[typeDefinition.name] = typeDefinition;
}
},
diff --git a/pkg/analyzer_plugin/tool/spec/generate_all.dart b/pkg/analyzer_plugin/tool/spec/generate_all.dart
index 6507475..3ce0b3c 100644
--- a/pkg/analyzer_plugin/tool/spec/generate_all.dart
+++ b/pkg/analyzer_plugin/tool/spec/generate_all.dart
@@ -28,7 +28,9 @@
targets.add(codegen_inttest_methods.target);
targets.add(codegen_matchers.target);
targets.add(codegen_protocol_common.pluginTarget(true));
- targets.add(codegen_protocol_common.clientTarget(true));
+ // TODO(scheglov) Migrate analysis_server_client
+ // https://github.com/dart-lang/sdk/issues/45500
+ // targets.add(codegen_protocol_common.clientTarget(true));
targets.add(codegen_protocol_constants.target);
targets.add(to_html.target);
return targets;
diff --git a/pkg/analyzer_plugin/tool/spec/implied_types.dart b/pkg/analyzer_plugin/tool/spec/implied_types.dart
index 04f217c..21e2639 100644
--- a/pkg/analyzer_plugin/tool/spec/implied_types.dart
+++ b/pkg/analyzer_plugin/tool/spec/implied_types.dart
@@ -16,7 +16,7 @@
class ImpliedType {
final String camelName;
final String humanReadableName;
- final TypeDecl type;
+ final TypeDecl? type;
/// Kind of implied type this is. One of:
/// - 'requestParams'
@@ -39,7 +39,7 @@
_ImpliedTypesVisitor(Api api) : super(api);
- void storeType(String name, String nameSuffix, TypeDecl type, String kind,
+ void storeType(String name, String? nameSuffix, TypeDecl? type, String kind,
ApiNode apiNode) {
var humanReadableName = name;
var camelNameParts = name.split('.');
diff --git a/pkg/analyzer_plugin/tool/spec/to_html.dart b/pkg/analyzer_plugin/tool/spec/to_html.dart
index 8c9ea33..b2d4d67 100644
--- a/pkg/analyzer_plugin/tool/spec/to_html.dart
+++ b/pkg/analyzer_plugin/tool/spec/to_html.dart
@@ -148,7 +148,7 @@
@override
void visitDomain(Domain domain) {
- domains[domain.html] = domain;
+ domains[domain.html!] = domain;
}
}
@@ -170,11 +170,11 @@
void dt(String cls, void Function() callback) =>
element('dt', {'class': cls}, callback);
void element(String name, Map<Object, String> attributes,
- [void Function() callback]);
+ [void Function()? callback]);
void gray(void Function() callback) =>
element('span', {'style': 'color:#999999'}, callback);
void h1(void Function() callback) => element('h1', {}, callback);
- void h2(String cls, void Function() callback) {
+ void h2(String? cls, void Function() callback) {
if (cls == null) {
return element('h2', {}, callback);
}
@@ -191,7 +191,7 @@
void i(void Function() callback) => element('i', {}, callback);
void li(void Function() callback) => element('li', {}, callback);
void link(String id, void Function() callback,
- [Map<dynamic, String> attributes]) {
+ [Map<Object, String>? attributes]) {
attributes ??= {};
attributes['href'] = '#$id';
element('a', attributes, callback);
@@ -226,7 +226,7 @@
///
/// If [force] is true, then a section is inserted even if the payload is
/// null.
- void describePayload(TypeObject subType, String name, {bool force = false}) {
+ void describePayload(TypeObject? subType, String name, {bool force = false}) {
if (force || subType != null) {
h4(() {
write(name);
@@ -279,7 +279,7 @@
}
generateTypesIndex(definedTypes);
- generateRefactoringsIndex(api.refactorings);
+ generateRefactoringsIndex(api.refactorings!);
}
void generateNotificationsIndex(Iterable<Notification> notifications) {
@@ -298,9 +298,6 @@
}
void generateRefactoringsIndex(Iterable<Refactoring> refactorings) {
- if (refactorings == null) {
- return;
- }
h3(() {
write('Refactorings');
write(' (');
@@ -384,13 +381,11 @@
}
void javadocParams(TypeObject typeObject) {
- if (typeObject != null) {
- for (var field in typeObject.fields) {
- hangingIndent(() {
- write('@param ${field.name} ');
- translateHtml(field.html, squashParagraphs: true);
- });
- }
+ for (var field in typeObject.fields) {
+ hangingIndent(() {
+ write('@param ${field.name} ');
+ translateHtml(field.html, squashParagraphs: true);
+ });
}
}
@@ -401,7 +396,8 @@
///
/// If [typeForBolding] is supplied, then fields in this type are shown in
/// boldface.
- void showType(String shortDesc, TypeDecl type, [TypeObject typeForBolding]) {
+ void showType(String? shortDesc, TypeDecl type,
+ [TypeObject? typeForBolding]) {
var fieldsToBold = <String>{};
if (typeForBolding != null) {
for (var field in typeForBolding.fields) {
@@ -421,7 +417,10 @@
/// Copy the contents of the given HTML element, translating the special
/// elements that define the API appropriately.
- void translateHtml(dom.Element html, {bool squashParagraphs = false}) {
+ void translateHtml(dom.Element? html, {bool squashParagraphs = false}) {
+ if (html == null) {
+ return;
+ }
for (var node in html.nodes) {
if (node is dom.Element) {
if (squashParagraphs && node.localName == 'p') {
@@ -433,7 +432,7 @@
generateDomainsHeader();
break;
case 'domain':
- visitDomain(apiMappings.domains[node]);
+ visitDomain(apiMappings.domains[node]!);
break;
case 'head':
head(() {
@@ -466,7 +465,7 @@
break;
default:
if (!ApiReader.specialElements.contains(node.localName)) {
- element(node.localName, node.attributes, () {
+ element(node.localName!, node.attributes, () {
translateHtml(node, squashParagraphs: squashParagraphs);
});
}
@@ -547,8 +546,8 @@
}
@override
- void visitRefactorings(Refactorings refactorings) {
- translateHtml(refactorings.html);
+ void visitRefactorings(Refactorings? refactorings) {
+ translateHtml(refactorings?.html);
dl(() {
super.visitRefactorings(refactorings);
});
@@ -609,7 +608,7 @@
@override
void visitTypeEnumValue(TypeEnumValue typeEnumValue) {
var isDocumented = false;
- for (var node in typeEnumValue.html.nodes) {
+ for (var node in typeEnumValue.html?.nodes ?? []) {
if ((node is dom.Element && node.localName != 'code') ||
(node is dom.Text && node.text.trim().isNotEmpty)) {
isDocumented = true;
@@ -701,7 +700,7 @@
with HtmlMixin, HtmlCodeGenerator {
/// Set of fields which should be shown in boldface, or null if no field
/// should be shown in boldface.
- final Set<String> fieldsToBold;
+ final Set<String>? fieldsToBold;
/// True if a short description should be generated. In a short description,
/// objects are shown as simply "object", and enums are shown as "String".
@@ -750,6 +749,7 @@
indent(() {
for (var field in typeObject.fields) {
write('"');
+ var fieldsToBold = this.fieldsToBold;
if (fieldsToBold != null && fieldsToBold.contains(field.name)) {
b(() {
write(field.name);
diff --git a/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart b/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
index 8041794..645bbd9 100644
--- a/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
@@ -3373,6 +3373,10 @@
new BreakStatus(node.target);
@override
+ ExecutionStatus visitContinueSwitchStatement(ContinueSwitchStatement node) =>
+ node.target.body.accept(this);
+
+ @override
ExecutionStatus visitDoStatement(DoStatement node) {
Constant condition;
do {
@@ -3454,6 +3458,21 @@
new ReturnStatus(evaluate(node.expression));
@override
+ ExecutionStatus visitSwitchStatement(SwitchStatement node) {
+ final Constant value = evaluate(node.expression);
+ if (value is AbortConstant) return new AbortStatus(value);
+
+ for (SwitchCase switchCase in node.cases) {
+ if (switchCase.isDefault) return switchCase.body.accept(this);
+ for (Expression expr in switchCase.expressions) {
+ final Constant caseValue = evaluate(expr);
+ if (value == caseValue) return switchCase.body.accept(this);
+ }
+ }
+ return const ProceedStatus();
+ }
+
+ @override
ExecutionStatus visitVariableDeclaration(VariableDeclaration node) {
Constant value = evaluate(node.initializer);
if (value is AbortConstant) return new AbortStatus(value);
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart
new file mode 100644
index 0000000..c192041
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart
@@ -0,0 +1,65 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Tests switch statements for const functions.
+
+import "package:expect/expect.dart";
+
+const var1 = basicSwitch(1);
+const var2 = basicSwitch(2);
+int basicSwitch(int x) {
+ switch (x) {
+ case 1:
+ return 100;
+ default:
+ x++;
+ break;
+ }
+ return x;
+}
+
+const var3 = multipleCaseSwitch(1);
+const var4 = multipleCaseSwitch(2);
+const var5 = multipleCaseSwitch(3);
+int multipleCaseSwitch(int x) {
+ switch (x) {
+ case 1:
+ case 2:
+ return 100;
+ default:
+ break;
+ }
+ return 0;
+}
+
+const var6 = continueLabelSwitch(1);
+const var7 = continueLabelSwitch(2);
+const var8 = continueLabelSwitch(3);
+const var9 = continueLabelSwitch(4);
+int continueLabelSwitch(int x) {
+ switch (x) {
+ label1:
+ case 1:
+ x = x + 100;
+ continue label3;
+ case 2:
+ continue label1;
+ label3:
+ case 3:
+ return x + 3;
+ }
+ return 0;
+}
+
+void main() {
+ Expect.equals(var1, 100);
+ Expect.equals(var2, 3);
+ Expect.equals(var3, 100);
+ Expect.equals(var4, 100);
+ Expect.equals(var5, 0);
+ Expect.equals(var6, 104);
+ Expect.equals(var7, 105);
+ Expect.equals(var8, 6);
+ Expect.equals(var9, 0);
+}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.expect
new file mode 100644
index 0000000..76efdb8
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.expect
@@ -0,0 +1,93 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+import "package:expect/expect.dart" as exp;
+
+import "package:expect/expect.dart";
+
+static const field core::int var1 = #C1;
+static const field core::int var2 = #C2;
+static const field core::int var3 = #C1;
+static const field core::int var4 = #C1;
+static const field core::int var5 = #C3;
+static const field core::int var6 = #C4;
+static const field core::int var7 = #C5;
+static const field core::int var8 = #C6;
+static const field core::int var9 = #C3;
+static method basicSwitch(core::int x) → core::int {
+ #L1:
+ switch(x) {
+ #L2:
+ case #C7:
+ {
+ return 100;
+ }
+ #L3:
+ default:
+ {
+ x = x.{core::num::+}(1);
+ break #L1;
+ }
+ }
+ return x;
+}
+static method multipleCaseSwitch(core::int x) → core::int {
+ #L4:
+ switch(x) {
+ #L5:
+ case #C7:
+ case #C8:
+ {
+ return 100;
+ }
+ #L6:
+ default:
+ {
+ break #L4;
+ }
+ }
+ return 0;
+}
+static method continueLabelSwitch(core::int x) → core::int {
+ switch(x) {
+ #L7:
+ case #C7:
+ {
+ x = x.{core::num::+}(100);
+ continue #L8;
+ }
+ #L9:
+ case #C8:
+ {
+ continue #L7;
+ }
+ #L8:
+ case #C2:
+ {
+ return x.{core::num::+}(3);
+ }
+ }
+ return 0;
+}
+static method main() → void {
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C2, 3);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C3, 0);
+ exp::Expect::equals(#C4, 104);
+ exp::Expect::equals(#C5, 105);
+ exp::Expect::equals(#C6, 6);
+ exp::Expect::equals(#C3, 0);
+}
+
+constants {
+ #C1 = 100
+ #C2 = 3
+ #C3 = 0
+ #C4 = 104
+ #C5 = 105
+ #C6 = 6
+ #C7 = 1
+ #C8 = 2
+}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.transformed.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.transformed.expect
new file mode 100644
index 0000000..76efdb8
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.strong.transformed.expect
@@ -0,0 +1,93 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+import "package:expect/expect.dart" as exp;
+
+import "package:expect/expect.dart";
+
+static const field core::int var1 = #C1;
+static const field core::int var2 = #C2;
+static const field core::int var3 = #C1;
+static const field core::int var4 = #C1;
+static const field core::int var5 = #C3;
+static const field core::int var6 = #C4;
+static const field core::int var7 = #C5;
+static const field core::int var8 = #C6;
+static const field core::int var9 = #C3;
+static method basicSwitch(core::int x) → core::int {
+ #L1:
+ switch(x) {
+ #L2:
+ case #C7:
+ {
+ return 100;
+ }
+ #L3:
+ default:
+ {
+ x = x.{core::num::+}(1);
+ break #L1;
+ }
+ }
+ return x;
+}
+static method multipleCaseSwitch(core::int x) → core::int {
+ #L4:
+ switch(x) {
+ #L5:
+ case #C7:
+ case #C8:
+ {
+ return 100;
+ }
+ #L6:
+ default:
+ {
+ break #L4;
+ }
+ }
+ return 0;
+}
+static method continueLabelSwitch(core::int x) → core::int {
+ switch(x) {
+ #L7:
+ case #C7:
+ {
+ x = x.{core::num::+}(100);
+ continue #L8;
+ }
+ #L9:
+ case #C8:
+ {
+ continue #L7;
+ }
+ #L8:
+ case #C2:
+ {
+ return x.{core::num::+}(3);
+ }
+ }
+ return 0;
+}
+static method main() → void {
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C2, 3);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C3, 0);
+ exp::Expect::equals(#C4, 104);
+ exp::Expect::equals(#C5, 105);
+ exp::Expect::equals(#C6, 6);
+ exp::Expect::equals(#C3, 0);
+}
+
+constants {
+ #C1 = 100
+ #C2 = 3
+ #C3 = 0
+ #C4 = 104
+ #C5 = 105
+ #C6 = 6
+ #C7 = 1
+ #C8 = 2
+}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline.expect
new file mode 100644
index 0000000..5d539a6
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline.expect
@@ -0,0 +1,15 @@
+import "package:expect/expect.dart";
+
+const var1 = basicSwitch(1);
+const var2 = basicSwitch(2);
+int basicSwitch(int x) {}
+const var3 = multipleCaseSwitch(1);
+const var4 = multipleCaseSwitch(2);
+const var5 = multipleCaseSwitch(3);
+int multipleCaseSwitch(int x) {}
+const var6 = continueLabelSwitch(1);
+const var7 = continueLabelSwitch(2);
+const var8 = continueLabelSwitch(3);
+const var9 = continueLabelSwitch(4);
+int continueLabelSwitch(int x) {}
+void main() {}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline_modelled.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline_modelled.expect
new file mode 100644
index 0000000..f57dab8
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.textual_outline_modelled.expect
@@ -0,0 +1,15 @@
+import "package:expect/expect.dart";
+
+const var1 = basicSwitch(1);
+const var2 = basicSwitch(2);
+const var3 = multipleCaseSwitch(1);
+const var4 = multipleCaseSwitch(2);
+const var5 = multipleCaseSwitch(3);
+const var6 = continueLabelSwitch(1);
+const var7 = continueLabelSwitch(2);
+const var8 = continueLabelSwitch(3);
+const var9 = continueLabelSwitch(4);
+int basicSwitch(int x) {}
+int continueLabelSwitch(int x) {}
+int multipleCaseSwitch(int x) {}
+void main() {}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.expect
new file mode 100644
index 0000000..76efdb8
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.expect
@@ -0,0 +1,93 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+import "package:expect/expect.dart" as exp;
+
+import "package:expect/expect.dart";
+
+static const field core::int var1 = #C1;
+static const field core::int var2 = #C2;
+static const field core::int var3 = #C1;
+static const field core::int var4 = #C1;
+static const field core::int var5 = #C3;
+static const field core::int var6 = #C4;
+static const field core::int var7 = #C5;
+static const field core::int var8 = #C6;
+static const field core::int var9 = #C3;
+static method basicSwitch(core::int x) → core::int {
+ #L1:
+ switch(x) {
+ #L2:
+ case #C7:
+ {
+ return 100;
+ }
+ #L3:
+ default:
+ {
+ x = x.{core::num::+}(1);
+ break #L1;
+ }
+ }
+ return x;
+}
+static method multipleCaseSwitch(core::int x) → core::int {
+ #L4:
+ switch(x) {
+ #L5:
+ case #C7:
+ case #C8:
+ {
+ return 100;
+ }
+ #L6:
+ default:
+ {
+ break #L4;
+ }
+ }
+ return 0;
+}
+static method continueLabelSwitch(core::int x) → core::int {
+ switch(x) {
+ #L7:
+ case #C7:
+ {
+ x = x.{core::num::+}(100);
+ continue #L8;
+ }
+ #L9:
+ case #C8:
+ {
+ continue #L7;
+ }
+ #L8:
+ case #C2:
+ {
+ return x.{core::num::+}(3);
+ }
+ }
+ return 0;
+}
+static method main() → void {
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C2, 3);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C3, 0);
+ exp::Expect::equals(#C4, 104);
+ exp::Expect::equals(#C5, 105);
+ exp::Expect::equals(#C6, 6);
+ exp::Expect::equals(#C3, 0);
+}
+
+constants {
+ #C1 = 100
+ #C2 = 3
+ #C3 = 0
+ #C4 = 104
+ #C5 = 105
+ #C6 = 6
+ #C7 = 1
+ #C8 = 2
+}
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.outline.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.outline.expect
new file mode 100644
index 0000000..b7050bd
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.outline.expect
@@ -0,0 +1,23 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+
+import "package:expect/expect.dart";
+
+static const field core::int var1 = self::basicSwitch(1);
+static const field core::int var2 = self::basicSwitch(2);
+static const field core::int var3 = self::multipleCaseSwitch(1);
+static const field core::int var4 = self::multipleCaseSwitch(2);
+static const field core::int var5 = self::multipleCaseSwitch(3);
+static const field core::int var6 = self::continueLabelSwitch(1);
+static const field core::int var7 = self::continueLabelSwitch(2);
+static const field core::int var8 = self::continueLabelSwitch(3);
+static const field core::int var9 = self::continueLabelSwitch(4);
+static method basicSwitch(core::int x) → core::int
+ ;
+static method multipleCaseSwitch(core::int x) → core::int
+ ;
+static method continueLabelSwitch(core::int x) → core::int
+ ;
+static method main() → void
+ ;
diff --git a/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.transformed.expect b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.transformed.expect
new file mode 100644
index 0000000..76efdb8
--- /dev/null
+++ b/pkg/front_end/testcases/const_functions/const_functions_switch_statements.dart.weak.transformed.expect
@@ -0,0 +1,93 @@
+library /*isNonNullableByDefault*/;
+import self as self;
+import "dart:core" as core;
+import "package:expect/expect.dart" as exp;
+
+import "package:expect/expect.dart";
+
+static const field core::int var1 = #C1;
+static const field core::int var2 = #C2;
+static const field core::int var3 = #C1;
+static const field core::int var4 = #C1;
+static const field core::int var5 = #C3;
+static const field core::int var6 = #C4;
+static const field core::int var7 = #C5;
+static const field core::int var8 = #C6;
+static const field core::int var9 = #C3;
+static method basicSwitch(core::int x) → core::int {
+ #L1:
+ switch(x) {
+ #L2:
+ case #C7:
+ {
+ return 100;
+ }
+ #L3:
+ default:
+ {
+ x = x.{core::num::+}(1);
+ break #L1;
+ }
+ }
+ return x;
+}
+static method multipleCaseSwitch(core::int x) → core::int {
+ #L4:
+ switch(x) {
+ #L5:
+ case #C7:
+ case #C8:
+ {
+ return 100;
+ }
+ #L6:
+ default:
+ {
+ break #L4;
+ }
+ }
+ return 0;
+}
+static method continueLabelSwitch(core::int x) → core::int {
+ switch(x) {
+ #L7:
+ case #C7:
+ {
+ x = x.{core::num::+}(100);
+ continue #L8;
+ }
+ #L9:
+ case #C8:
+ {
+ continue #L7;
+ }
+ #L8:
+ case #C2:
+ {
+ return x.{core::num::+}(3);
+ }
+ }
+ return 0;
+}
+static method main() → void {
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C2, 3);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C1, 100);
+ exp::Expect::equals(#C3, 0);
+ exp::Expect::equals(#C4, 104);
+ exp::Expect::equals(#C5, 105);
+ exp::Expect::equals(#C6, 6);
+ exp::Expect::equals(#C3, 0);
+}
+
+constants {
+ #C1 = 100
+ #C2 = 3
+ #C3 = 0
+ #C4 = 104
+ #C5 = 105
+ #C6 = 6
+ #C7 = 1
+ #C8 = 2
+}
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.expect
index 0564c29..d997209 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.expect
@@ -25,4 +25,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.transformed.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.transformed.expect
index a943907..62cdedc 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.strong.transformed.expect
@@ -51,4 +51,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.expect
index 3637817..f04b75d 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.expect
@@ -25,4 +25,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.transformed.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.transformed.expect
index 77bed60..85a31bd 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array.dart.weak.transformed.expect
@@ -51,4 +51,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.expect
index 7d5a7e1..391f4bc 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.expect
@@ -33,4 +33,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array_multi_dimensional.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.transformed.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.transformed.expect
index 6ccde5b..f190d80 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.strong.transformed.expect
@@ -83,4 +83,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array_multi_dimensional.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.expect
index 4f90a79..32510af 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.expect
@@ -33,4 +33,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array_multi_dimensional.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.transformed.expect b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.transformed.expect
index 2147809..abf15e4 100644
--- a/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/ffi_struct_inline_array_multi_dimensional.dart.weak.transformed.expect
@@ -83,4 +83,4 @@
Constructor coverage from constants:
org-dartlang-testcase:///ffi_struct_inline_array_multi_dimensional.dart:
-- _ArraySize. (from org-dartlang-sdk:///sdk/lib/_internal/vm/lib/ffi_patch.dart:156:9)
+- _ArraySize. (from org-dartlang-sdk:///sdk/lib/ffi/ffi.dart:134:9)
diff --git a/pkg/test_runner/bin/test_runner.dart b/pkg/test_runner/bin/test_runner.dart
index 7cb77ae..1c2d26a 100644
--- a/pkg/test_runner/bin/test_runner.dart
+++ b/pkg/test_runner/bin/test_runner.dart
@@ -37,6 +37,7 @@
print(exception.message);
exit(1);
}
+
if (configurations.isEmpty) return;
await buildConfigurations(configurations);
// Run all of the configured tests.
diff --git a/pkg/test_runner/lib/src/options.dart b/pkg/test_runner/lib/src/options.dart
index 1d2b814..b002c93 100644
--- a/pkg/test_runner/lib/src/options.dart
+++ b/pkg/test_runner/lib/src/options.dart
@@ -426,7 +426,7 @@
if (arguments.contains("--help") || arguments.contains("-h")) {
_printHelp(
verbose: arguments.contains("--verbose") || arguments.contains("-v"));
- return null;
+ return const [];
}
// Parse the command line arguments to a map.
@@ -563,12 +563,12 @@
if (options.containsKey('find-configurations')) {
findConfigurations(options);
- return null;
+ return const [];
}
if (options.containsKey('list-configurations')) {
listConfigurations(options);
- return null;
+ return const [];
}
// If a named configuration was specified ensure no other options, which are
diff --git a/runtime/vm/compiler/jit/compiler.cc b/runtime/vm/compiler/jit/compiler.cc
index 9b5c55e..77683fa 100644
--- a/runtime/vm/compiler/jit/compiler.cc
+++ b/runtime/vm/compiler/jit/compiler.cc
@@ -612,11 +612,8 @@
// breakpoint.
if (!result->IsNull()) {
if (!function.HasOptimizedCode()) {
- thread()->isolate_group()->ForEachIsolate(
- [&](Isolate* isolate) {
- isolate->debugger()->NotifyCompilation(function);
- },
- /*at_safepoint=*/true);
+ thread()->isolate_group()->debugger()->NotifyCompilation(
+ function);
}
}
#endif
diff --git a/runtime/vm/debugger.cc b/runtime/vm/debugger.cc
index eb95276..e90e6ad 100644
--- a/runtime/vm/debugger.cc
+++ b/runtime/vm/debugger.cc
@@ -66,6 +66,7 @@
: debugger_(debugger),
script_(script.ptr()),
url_(script.url()),
+ line_number_lock_(new SafepointRwLock()),
line_number_(-1), // lazily computed
token_pos_(token_pos),
end_token_pos_(end_token_pos),
@@ -86,6 +87,8 @@
: debugger_(debugger),
script_(Script::null()),
url_(url.ptr()),
+ line_number_lock_(new SafepointRwLock()),
+ line_number_(-1), // lazily computed
token_pos_(TokenPosition::kNoSource),
end_token_pos_(TokenPosition::kNoSource),
next_(NULL),
@@ -131,6 +134,21 @@
}
}
+intptr_t BreakpointLocation::line_number() {
+ // Compute line number lazily since it causes scanning of the script.
+ {
+ SafepointReadRwLocker sl(Thread::Current(), line_number_lock());
+ if (line_number_ >= 0) {
+ return line_number_;
+ }
+ }
+ SafepointWriteRwLocker sl(Thread::Current(), line_number_lock());
+ if (line_number_ < 0) {
+ Script::Handle(script()).GetTokenLocation(token_pos(), &line_number_);
+ }
+ return line_number_;
+}
+
void Breakpoint::set_bpt_location(BreakpointLocation* new_bpt_location) {
// Only latent breakpoints can be moved.
ASSERT((new_bpt_location == NULL) || bpt_location_->IsLatent());
@@ -1539,6 +1557,7 @@
: isolate_group_(isolate_group),
code_breakpoints_lock_(new SafepointRwLock()),
code_breakpoints_(nullptr),
+ breakpoint_locations_lock_(new SafepointRwLock()),
needs_breakpoint_cleanup_(false) {}
GroupDebugger::~GroupDebugger() {
@@ -1587,17 +1606,23 @@
if (Isolate::IsSystemIsolate(isolate_)) {
return;
}
- while (breakpoint_locations_ != nullptr) {
- BreakpointLocation* loc = breakpoint_locations_;
- group_debugger()->UnlinkCodeBreakpoints(loc);
- breakpoint_locations_ = breakpoint_locations_->next();
- delete loc;
- }
- while (latent_locations_ != nullptr) {
- BreakpointLocation* loc = latent_locations_;
- group_debugger()->UnlinkCodeBreakpoints(loc);
- latent_locations_ = latent_locations_->next();
- delete loc;
+ {
+ SafepointWriteRwLocker sl(Thread::Current(),
+ group_debugger()->breakpoint_locations_lock());
+ while (breakpoint_locations_ != nullptr) {
+ BreakpointLocation* loc = breakpoint_locations_;
+ group_debugger()->UnlinkCodeBreakpoints(loc);
+ group_debugger()->UnregisterBreakpointLocation(loc);
+ breakpoint_locations_ = breakpoint_locations_->next();
+ delete loc;
+ }
+ while (latent_locations_ != nullptr) {
+ BreakpointLocation* loc = latent_locations_;
+ group_debugger()->UnlinkCodeBreakpoints(loc);
+ group_debugger()->UnregisterBreakpointLocation(loc);
+ latent_locations_ = latent_locations_->next();
+ delete loc;
+ }
}
if (NeedsIsolateEvents()) {
ServiceEvent event(isolate_, ServiceEvent::kIsolateExit);
@@ -2537,33 +2562,35 @@
}
}
}
- if (lowest_pc_offset != kUwordMax) {
- uword lowest_pc = code.PayloadStart() + lowest_pc_offset;
- SafepointWriteRwLocker sl(Thread::Current(), code_breakpoints_lock());
- CodeBreakpoint* code_bpt = GetCodeBreakpoint(lowest_pc);
- if (code_bpt == nullptr) {
- // No code breakpoint for this code exists; create one.
- code_bpt = new CodeBreakpoint(code, loc, lowest_pc, lowest_kind);
- if (FLAG_verbose_debug) {
- OS::PrintErr("Setting code breakpoint at pos %s pc %#" Px
- " offset %#" Px "\n",
- loc->token_pos_.ToCString(), lowest_pc,
- lowest_pc - code.PayloadStart());
- }
- RegisterCodeBreakpoint(code_bpt);
- } else {
- if (FLAG_verbose_debug) {
- OS::PrintErr(
- "Adding location to existing code breakpoint at pos %s pc %#" Px
- " offset %#" Px "\n",
- loc->token_pos_.ToCString(), lowest_pc,
- lowest_pc - code.PayloadStart());
- }
- code_bpt->AddBreakpointLocation(loc);
+ if (lowest_pc_offset == kUwordMax) {
+ return;
+ }
+
+ uword lowest_pc = code.PayloadStart() + lowest_pc_offset;
+ SafepointWriteRwLocker sl(Thread::Current(), code_breakpoints_lock());
+ CodeBreakpoint* code_bpt = GetCodeBreakpoint(lowest_pc);
+ if (code_bpt == nullptr) {
+ // No code breakpoint for this code exists; create one.
+ code_bpt = new CodeBreakpoint(code, loc, lowest_pc, lowest_kind);
+ if (FLAG_verbose_debug) {
+ OS::PrintErr("Setting code breakpoint at pos %s pc %#" Px " offset %#" Px
+ "\n",
+ loc->token_pos_.ToCString(), lowest_pc,
+ lowest_pc - code.PayloadStart());
}
- if (loc->AnyEnabled()) {
- code_bpt->Enable();
+ RegisterCodeBreakpoint(code_bpt);
+ } else {
+ if (FLAG_verbose_debug) {
+ OS::PrintErr(
+ "Adding location to existing code breakpoint at pos %s pc %#" Px
+ " offset %#" Px "\n",
+ loc->token_pos_.ToCString(), lowest_pc,
+ lowest_pc - code.PayloadStart());
}
+ code_bpt->AddBreakpointLocation(loc);
+ }
+ if (loc->AnyEnabled()) {
+ code_bpt->Enable();
}
}
@@ -3126,6 +3153,102 @@
return loc;
}
+// Return innermost closure contained in 'function' that contains
+// the given token position.
+static FunctionPtr FindInnermostClosure(Zone* zone,
+ const Function& function,
+ TokenPosition token_pos) {
+ ASSERT(function.end_token_pos().IsReal());
+ const TokenPosition& func_start = function.token_pos();
+ const Script& outer_origin = Script::Handle(zone, function.script());
+
+ Function& best_fit = Function::Handle(zone);
+ ClosureFunctionsCache::ForAllClosureFunctions([&](const Function& closure) {
+ const TokenPosition& closure_start = closure.token_pos();
+ const TokenPosition& closure_end = closure.end_token_pos();
+ // We're only interested in closures that have real ending token positions.
+ // The starting token position can be synthetic.
+ if (closure_end.IsReal() && (function.end_token_pos() > closure_end) &&
+ (!closure_start.IsReal() || !func_start.IsReal() ||
+ (closure_start > func_start)) &&
+ token_pos.IsWithin(closure_start, closure_end) &&
+ (closure.script() == outer_origin.ptr())) {
+ UpdateBestFit(&best_fit, closure);
+ }
+ return true; // Continue iteration.
+ });
+ return best_fit.ptr();
+}
+
+bool GroupDebugger::EnsureLocationIsInFunction(Zone* zone,
+ const Function& function,
+ BreakpointLocation* location) {
+ const Script& script = Script::Handle(zone, location->script());
+ if (!FunctionOverlaps(function, script, location->token_pos(),
+ location->end_token_pos())) {
+ return false;
+ }
+
+ TokenPosition token_pos = location->token_pos();
+#if !defined(DART_PRECOMPILED_RUNTIME)
+ TokenPosition end_token_pos = location->end_token_pos();
+ if (token_pos != end_token_pos && location->requested_column_number() >= 0) {
+ // Narrow down the token position range to a single value
+ // if requested column number is provided so that inner
+ // Closure won't be missed.
+ token_pos = FindExactTokenPosition(script, token_pos,
+ location->requested_column_number());
+ }
+#endif // !defined(DART_PRECOMPILED_RUNTIME)
+ const Function& inner_function =
+ Function::Handle(zone, FindInnermostClosure(zone, function, token_pos));
+ if (!inner_function.IsNull()) {
+ if (FLAG_verbose_debug) {
+ OS::PrintErr(
+ "Pending breakpoint remains unresolved in "
+ "inner function '%s'\n",
+ inner_function.ToFullyQualifiedCString());
+ }
+ return false;
+ }
+
+ // There is no local function within function that contains the
+ // breakpoint token position. Resolve the breakpoint if necessary
+ // and set the code breakpoints.
+ if (!location->EnsureIsResolved(function, token_pos)) {
+ // Failed to resolve breakpoint location for some reason
+ return false;
+ }
+ return true;
+}
+
+void GroupDebugger::NotifyCompilation(const Function& function) {
+ if (!function.is_debuggable()) {
+ return;
+ }
+ auto thread = Thread::Current();
+ auto zone = thread->zone();
+
+ // Going through BreakpointLocations of all isolates and debuggers looking
+ // for those that can be resolved and added code breakpoints at now.
+ SafepointReadRwLocker sl(thread, breakpoint_locations_lock());
+ for (intptr_t i = 0; i < breakpoint_locations_.length(); i++) {
+ BreakpointLocation* location = breakpoint_locations_.At(i);
+ if (EnsureLocationIsInFunction(zone, function, location)) {
+ if (FLAG_verbose_debug) {
+ Breakpoint* bpt = location->breakpoints();
+ while (bpt != NULL) {
+ OS::PrintErr("Setting breakpoint %" Pd " for %s '%s'\n", bpt->id(),
+ function.IsClosureFunction() ? "closure" : "function",
+ function.ToFullyQualifiedCString());
+ bpt = bpt->next();
+ }
+ }
+ MakeCodeBreakpointAt(function, location);
+ }
+ }
+}
+
void GroupDebugger::VisitObjectPointers(ObjectPointerVisitor* visitor) {
CodeBreakpoint* cbpt = code_breakpoints_;
while (cbpt != nullptr) {
@@ -3928,34 +4051,6 @@
}
}
-// Return innermost closure contained in 'function' that contains
-// the given token position.
-static FunctionPtr FindInnermostClosure(const Function& function,
- TokenPosition token_pos) {
- ASSERT(function.end_token_pos().IsReal());
- const TokenPosition& func_start = function.token_pos();
- auto thread = Thread::Current();
- auto zone = thread->zone();
- const Script& outer_origin = Script::Handle(zone, function.script());
-
- Function& best_fit = Function::Handle(zone);
- ClosureFunctionsCache::ForAllClosureFunctions([&](const Function& closure) {
- const TokenPosition& closure_start = closure.token_pos();
- const TokenPosition& closure_end = closure.end_token_pos();
- // We're only interested in closures that have real ending token positions.
- // The starting token position can be synthetic.
- if (closure_end.IsReal() && (function.end_token_pos() > closure_end) &&
- (!closure_start.IsReal() || !func_start.IsReal() ||
- (closure_start > func_start)) &&
- token_pos.IsWithin(closure_start, closure_end) &&
- (closure.script() == outer_origin.ptr())) {
- UpdateBestFit(&best_fit, closure);
- }
- return true; // Continue iteration.
- });
- return best_fit.ptr();
-}
-
#if !defined(DART_PRECOMPILED_RUNTIME)
// On single line of code with given column number,
// Calculate exact tokenPosition
@@ -3972,70 +4067,6 @@
}
#endif // !defined(DART_PRECOMPILED_RUNTIME)
-void Debugger::NotifyCompilation(const Function& func) {
- if (breakpoint_locations_ == NULL) {
- // Return with minimal overhead if there are no breakpoints.
- return;
- }
- if (!func.is_debuggable()) {
- // Nothing to do if the function is not debuggable. If there is
- // a pending breakpoint in an inner function (that is debuggable),
- // we'll resolve the breakpoint when the inner function is compiled.
- return;
- }
- // Iterate over all source breakpoints to check whether breakpoints
- // need to be set in the newly compiled function.
- Zone* zone = Thread::Current()->zone();
- Script& script = Script::Handle(zone);
- for (BreakpointLocation* loc = breakpoint_locations_; loc != NULL;
- loc = loc->next()) {
- script = loc->script();
- if (FunctionOverlaps(func, script, loc->token_pos(),
- loc->end_token_pos())) {
- TokenPosition token_pos = loc->token_pos();
- TokenPosition end_token_pos = loc->end_token_pos();
- if (token_pos != end_token_pos && loc->requested_column_number() >= 0) {
-#if !defined(DART_PRECOMPILED_RUNTIME)
- // Narrow down the token position range to a single value
- // if requested column number is provided so that inner
- // Closure won't be missed.
- token_pos = FindExactTokenPosition(script, token_pos,
- loc->requested_column_number());
-#endif // !defined(DART_PRECOMPILED_RUNTIME)
- }
- const Function& inner_function =
- Function::Handle(zone, FindInnermostClosure(func, token_pos));
- if (!inner_function.IsNull()) {
- if (FLAG_verbose_debug) {
- OS::PrintErr(
- "Pending breakpoint remains unresolved in "
- "inner function '%s'\n",
- inner_function.ToFullyQualifiedCString());
- }
- continue;
- }
-
- // There is no local function within func that contains the
- // breakpoint token position. Resolve the breakpoint if necessary
- // and set the code breakpoints.
- if (!loc->EnsureIsResolved(func, token_pos)) {
- // Failed to resolve breakpoint location for some reason
- continue;
- }
- if (FLAG_verbose_debug) {
- Breakpoint* bpt = loc->breakpoints();
- while (bpt != NULL) {
- OS::PrintErr("Setting breakpoint %" Pd " for %s '%s'\n", bpt->id(),
- func.IsClosureFunction() ? "closure" : "function",
- func.ToFullyQualifiedCString());
- bpt = bpt->next();
- }
- }
- group_debugger()->MakeCodeBreakpointAt(func, loc);
- }
- }
-}
-
void Debugger::NotifyDoneLoading() {
if (latent_locations_ == NULL) {
// Common, fast path.
@@ -4210,6 +4241,8 @@
// Remove and delete the source breakpoint bpt and its associated
// code breakpoints.
void Debugger::RemoveBreakpoint(intptr_t bp_id) {
+ SafepointWriteRwLocker sl(Thread::Current(),
+ group_debugger()->breakpoint_locations_lock());
if (RemoveBreakpointFromTheList(bp_id, &breakpoint_locations_)) {
return;
}
@@ -4265,6 +4298,7 @@
// Latent breakpoint locations won't have code breakpoints.
group_debugger()->UnlinkCodeBreakpoints(curr_loc);
}
+ group_debugger()->UnregisterBreakpointLocation(curr_loc);
BreakpointLocation* next_loc = curr_loc->next();
delete curr_loc;
curr_loc = next_loc;
@@ -4285,6 +4319,21 @@
return false;
}
+void GroupDebugger::RegisterBreakpointLocation(BreakpointLocation* location) {
+ ASSERT(breakpoint_locations_lock()->IsCurrentThreadWriter());
+ breakpoint_locations_.Add(location);
+}
+
+void GroupDebugger::UnregisterBreakpointLocation(BreakpointLocation* location) {
+ ASSERT(breakpoint_locations_lock()->IsCurrentThreadWriter());
+ for (intptr_t i = 0; i < breakpoint_locations_.length(); i++) {
+ if (breakpoint_locations_.At(i) == location) {
+ breakpoint_locations_.EraseAt(i);
+ return;
+ }
+ }
+}
+
// Unlink code breakpoints from the given breakpoint location.
// They will later be deleted when control returns from the pause event
// callback. Also, disable the breakpoint so it no longer fires if it
@@ -4427,9 +4476,12 @@
}
void Debugger::RegisterBreakpointLocation(BreakpointLocation* loc) {
+ SafepointWriteRwLocker sl(Thread::Current(),
+ group_debugger()->breakpoint_locations_lock());
ASSERT(loc->next() == NULL);
loc->set_next(breakpoint_locations_);
breakpoint_locations_ = loc;
+ group_debugger()->RegisterBreakpointLocation(loc);
}
#endif // !PRODUCT
diff --git a/runtime/vm/debugger.h b/runtime/vm/debugger.h
index b1bf176..29b7092 100644
--- a/runtime/vm/debugger.h
+++ b/runtime/vm/debugger.h
@@ -139,13 +139,7 @@
~BreakpointLocation();
TokenPosition token_pos() const { return token_pos_; }
- intptr_t line_number() {
- // Compute line number lazily since it causes scanning of the script.
- if (line_number_ < 0) {
- Script::Handle(script()).GetTokenLocation(token_pos(), &line_number_);
- }
- return line_number_;
- }
+ intptr_t line_number();
TokenPosition end_token_pos() const { return end_token_pos_; }
ScriptPtr script() const { return script_; }
@@ -187,9 +181,12 @@
// Finds the breakpoint we hit at |location|.
Breakpoint* FindHitBreakpoint(ActivationFrame* top_frame);
+ SafepointRwLock* line_number_lock() { return line_number_lock_.get(); }
+
Debugger* debugger_;
ScriptPtr script_;
StringPtr url_;
+ std::unique_ptr<SafepointRwLock> line_number_lock_;
intptr_t line_number_; // lazily computed for token_pos_
TokenPosition token_pos_;
TokenPosition end_token_pos_;
@@ -528,6 +525,7 @@
~GroupDebugger();
void MakeCodeBreakpointAt(const Function& func, BreakpointLocation* bpt);
+
// Returns [nullptr] if no breakpoint exists for the given address.
CodeBreakpoint* GetCodeBreakpoint(uword breakpoint_address);
BreakpointLocation* GetBreakpointLocationFor(Debugger* debugger,
@@ -535,6 +533,10 @@
CodeBreakpoint** pcbpt);
CodePtr GetPatchedStubAddress(uword breakpoint_address);
+ void RegisterBreakpointLocation(BreakpointLocation* location);
+ void UnregisterBreakpointLocation(BreakpointLocation* location);
+
+ void RemoveBreakpointLocation(BreakpointLocation* bpt_location);
void UnlinkCodeBreakpoints(BreakpointLocation* bpt_location);
// Returns true if the call at address pc is patched to point to
@@ -550,14 +552,29 @@
void Pause();
+ bool EnsureLocationIsInFunction(Zone* zone,
+ const Function& function,
+ BreakpointLocation* location);
+ void NotifyCompilation(const Function& func);
+
void VisitObjectPointers(ObjectPointerVisitor* visitor);
+ SafepointRwLock* breakpoint_locations_lock() {
+ return breakpoint_locations_lock_.get();
+ }
+
private:
IsolateGroup* isolate_group_;
std::unique_ptr<SafepointRwLock> code_breakpoints_lock_;
CodeBreakpoint* code_breakpoints_;
+ // Secondary list of all breakpoint_locations_(primary is in Debugger class).
+ // This list is kept in sync with all the lists in Isolate Debuggers and is
+ // used to quickly scan BreakpointLocations when new Function is compiled.
+ std::unique_ptr<SafepointRwLock> breakpoint_locations_lock_;
+ MallocGrowableArray<BreakpointLocation*> breakpoint_locations_;
+
SafepointRwLock* code_breakpoints_lock() {
return code_breakpoints_lock_.get();
}
@@ -584,7 +601,6 @@
void NotifyIsolateCreated();
void Shutdown();
- void NotifyCompilation(const Function& func);
void NotifyDoneLoading();
// Set breakpoint at closest location to function entry.
diff --git a/sdk/lib/_internal/vm/lib/ffi_patch.dart b/sdk/lib/_internal/vm/lib/ffi_patch.dart
index d2b0d0a..c9c3861 100644
--- a/sdk/lib/_internal/vm/lib/ffi_patch.dart
+++ b/sdk/lib/_internal/vm/lib/ffi_patch.dart
@@ -132,37 +132,6 @@
throw RangeError.range(index, 0, _size - 1);
}
}
-
- @patch
- const factory Array(int dimension1,
- [int dimension2,
- int dimension3,
- int dimension4,
- int dimension5]) = _ArraySize<T>;
-
- @patch
- const factory Array.multi(List<int> dimensions) = _ArraySize<T>.multi;
-}
-
-class _ArraySize<T extends NativeType> implements Array<T> {
- final int? dimension1;
- final int? dimension2;
- final int? dimension3;
- final int? dimension4;
- final int? dimension5;
-
- final List<int>? dimensions;
-
- const _ArraySize(this.dimension1,
- [this.dimension2, this.dimension3, this.dimension4, this.dimension5])
- : dimensions = null;
-
- const _ArraySize.multi(this.dimensions)
- : dimension1 = null,
- dimension2 = null,
- dimension3 = null,
- dimension4 = null,
- dimension5 = null;
}
/// Returns an integer encoding the ABI used for size and alignment
diff --git a/sdk/lib/ffi/ffi.dart b/sdk/lib/ffi/ffi.dart
index aff81e2..733c8fe 100644
--- a/sdk/lib/ffi/ffi.dart
+++ b/sdk/lib/ffi/ffi.dart
@@ -100,8 +100,11 @@
/// ```
///
/// Do not invoke in normal code.
- external const factory Array(int dimension1,
- [int dimension2, int dimension3, int dimension4, int dimension5]);
+ const factory Array(int dimension1,
+ [int dimension2,
+ int dimension3,
+ int dimension4,
+ int dimension5]) = _ArraySize<T>;
/// Const constructor to specify [Array] dimensions in [Struct]s.
///
@@ -116,7 +119,28 @@
/// ```
///
/// Do not invoke in normal code.
- external const factory Array.multi(List<int> dimensions);
+ const factory Array.multi(List<int> dimensions) = _ArraySize<T>.multi;
+}
+
+class _ArraySize<T extends NativeType> implements Array<T> {
+ final int? dimension1;
+ final int? dimension2;
+ final int? dimension3;
+ final int? dimension4;
+ final int? dimension5;
+
+ final List<int>? dimensions;
+
+ const _ArraySize(this.dimension1,
+ [this.dimension2, this.dimension3, this.dimension4, this.dimension5])
+ : dimensions = null;
+
+ const _ArraySize.multi(this.dimensions)
+ : dimension1 = null,
+ dimension2 = null,
+ dimension3 = null,
+ dimension4 = null,
+ dimension5 = null;
}
/// Extension on [Pointer] specialized for the type argument [NativeFunction].
diff --git a/tests/co19/co19-co19.status b/tests/co19/co19-co19.status
index 1f9cd40..baf4965 100644
--- a/tests/co19/co19-co19.status
+++ b/tests/co19/co19-co19.status
@@ -5,262 +5,3 @@
LibTest/ffi/Array/PointerArray_A01_t01: Skip # https://github.com/dart-lang/co19/issues/1018
LibTest/io/RawDatagramSocket/*: Skip # https://github.com/dart-lang/co19/issues/195
-[ $compiler != fasta ]
-Language/Classes/Abstract_Instance_Members/inherited_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/inherited_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/inherited_t15: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/invocation_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/invocation_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/override_default_value_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/override_less_positional_parameters_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/override_more_required_parameters_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/override_no_named_parameters_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/override_not_a_subtype_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Abstract_Instance_Members/same_name_static_method_in_superclass_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Constant_Constructors/name_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Constant_Constructors/not_a_constant_in_superclass_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Constant_Constructors/superinitializer_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Constant_Constructors/superinitializer_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/name_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/name_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/redirecting_to_itself_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/redirecting_to_itself_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/redirecting_to_itself_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/return_type_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/return_wrong_type_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/return_wrong_type_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Factories/return_wrong_type_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/execution_of_a_superinitializer_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/formal_parameter_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/formal_parameter_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/formal_parameter_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/implicit_superinitializer_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/implicit_superinitializer_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/initializers_t17: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/name_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/Generative_Constructors/superinitializer_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/implicit_constructor_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/implicit_constructor_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/name_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/wrong_name_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Constructors/wrong_name_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/instance_getter_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/instance_getter_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/override_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/same_name_method_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/same_name_method_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Getters/type_object_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_different_default_values_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_fewer_parameters_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_more_parameters_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_named_parameters_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_named_parameters_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_named_parameters_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_named_parameters_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_named_parameters_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/override_subtype_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/same_name_getter_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/same_name_setter_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/same_name_static_member_in_superclass_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Methods/same_name_static_member_in_superclass_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Variables/definition_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Variables/type_aliases_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Variables/type_aliases_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Instance_Variables/type_aliases_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Setters/syntax_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Static_Methods/declaration_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Static_Variables/inheritance_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Static_Variables/type_alias_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/abstract_method_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/inheritance_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/inheritance_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/inheritance_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/overriding_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/overriding_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/Inheritance_and_Overriding/overriding_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/extends_clause_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/superclass_of_itself_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/superclass_of_itself_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superclasses/transition_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/dynamic_type_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/implicit_interface_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/itself_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/more_than_once_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/no_member_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/no_member_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/superclass_as_superinterface_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/superclass_as_superinterface_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/superclass_as_superinterface_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Classes/Superinterfaces/syntax_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Enums/restrictions_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Enums/restrictions_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Enums/restrictions_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Enums/restrictions_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Enums/syntax_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Expressions/Instance_Creation/New/type_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Expressions/Instance_Creation/New/type_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/Superbounded_types/typedef3_A01_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A01_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A01_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A02_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A03_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A04_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/parameter_A09_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t20: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t21: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t22: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t23: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t24: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t25: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t27: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t28: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t29: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/syntax_t30: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A01_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A04_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A04_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A06_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A07_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A08_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A09_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A09_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Generics/typedef_A10_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/inheritance_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/not_overriden_members_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/not_overriden_members_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_getters_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_getters_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_getters_type_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_getters_type_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_getters_type_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_members_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/Inheritance_and_Overriding/same_name_method_and_getter_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/definition_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Interfaces/Superinterfaces/superinterface_of_itself_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/abstract_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/abstract_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/abstract_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/abstract_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/abstract_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/deferred_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/implicit_constructor_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/implicit_constructor_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/initializers_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/initializers_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/initializers_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/interfaces_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/interfaces_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superclass_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superclass_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superinterfaces_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superinterfaces_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superinterfaces_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superinterfaces_t13: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/superinterfaces_t14: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/syntax_t26: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/warning_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Application/wrong_mixin_type_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/Mixin_Composition/order_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Mixins/declaring_constructor_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t07: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t08: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t09: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t10: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t11: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/built-in_types_t12: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/scope_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/scope_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/scope_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/scope_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t19: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t20: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t21: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t22: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t23: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t24: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/self_reference_t25: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t01: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t02: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t03: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t04: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t05: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t06: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t20: Skip # github.com/dart-lang/language/issues/115
-Language/Types/Type_Aliases/syntax_t21: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Instantiate-to-bound/nonfunction_typedef/dynamic/*: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Instantiate-to-bound/nonfunction_typedef/static/*: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_FutureOr_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_FutureOr_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l1_t03: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l1_t04: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l2_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_l2_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t03: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t04: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t05: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t07: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/dynamic/typedef1_typedef_l1_t08: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_FutureOr_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_FutureOr_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l1_t03: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l1_t04: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l2_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_l2_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t01: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t03: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t04: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t05: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t06: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t07: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/Simple-bounds/static/typedef1_typedef_l1_t08: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/regression/32903_t02: Skip # github.com/dart-lang/language/issues/115
-LanguageFeatures/regression/34560_t02: Skip # github.com/dart-lang/language/issues/115
diff --git a/tests/ffi/regress_45507_test.dart b/tests/ffi/regress_45507_test.dart
new file mode 100644
index 0000000..9f46552
--- /dev/null
+++ b/tests/ffi/regress_45507_test.dart
@@ -0,0 +1,18 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:ffi";
+
+import "package:expect/expect.dart";
+
+const EIGHT = 8;
+
+class Struct8BytesInlineArrayInt extends Struct {
+ @Array(EIGHT)
+ external Array<Uint8> a0;
+}
+
+void main() {
+ Expect.equals(8, sizeOf<Struct8BytesInlineArrayInt>());
+}
diff --git a/tests/ffi/vmspecific_static_checks_test.dart b/tests/ffi/vmspecific_static_checks_test.dart
index e70f9963..72636d8 100644
--- a/tests/ffi/vmspecific_static_checks_test.dart
+++ b/tests/ffi/vmspecific_static_checks_test.dart
@@ -58,6 +58,7 @@
testRefStruct();
testSizeOfGeneric();
testSizeOfNativeType();
+ testSizeOfHandle();
testElementAtGeneric();
testElementAtNativeType();
}
@@ -636,11 +637,11 @@
}
void testSizeOfNativeType() {
- try {
- sizeOf(); //# 1301: compile-time error
- } catch (e) {
- print(e);
- }
+ sizeOf(); //# 1301: compile-time error
+}
+
+void testSizeOfHandle() {
+ sizeOf<Handle>(); //# 1302: compile-time error
}
void testElementAtGeneric() {
diff --git a/tests/ffi_2/regress_45507_test.dart b/tests/ffi_2/regress_45507_test.dart
new file mode 100644
index 0000000..926c719
--- /dev/null
+++ b/tests/ffi_2/regress_45507_test.dart
@@ -0,0 +1,18 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "dart:ffi";
+
+import "package:expect/expect.dart";
+
+const EIGHT = 8;
+
+class Struct8BytesInlineArrayInt extends Struct {
+ @Array(EIGHT)
+ Array<Uint8> a0;
+}
+
+void main() {
+ Expect.equals(8, sizeOf<Struct8BytesInlineArrayInt>());
+}
diff --git a/tests/ffi_2/vmspecific_static_checks_test.dart b/tests/ffi_2/vmspecific_static_checks_test.dart
index 3960181..3ae9b04 100644
--- a/tests/ffi_2/vmspecific_static_checks_test.dart
+++ b/tests/ffi_2/vmspecific_static_checks_test.dart
@@ -58,6 +58,7 @@
testRefStruct();
testSizeOfGeneric();
testSizeOfNativeType();
+ testSizeOfHandle();
testElementAtGeneric();
testElementAtNativeType();
}
@@ -634,11 +635,11 @@
}
void testSizeOfNativeType() {
- try {
- sizeOf(); //# 1301: compile-time error
- } catch (e) {
- print(e);
- }
+ sizeOf(); //# 1301: compile-time error
+}
+
+void testSizeOfHandle() {
+ sizeOf<Handle>(); //# 1302: compile-time error
}
void testElementAtGeneric() {
diff --git a/tests/language/const_functions/const_functions_switch_statements_error_test.dart b/tests/language/const_functions/const_functions_switch_statements_error_test.dart
new file mode 100644
index 0000000..659e3a4
--- /dev/null
+++ b/tests/language/const_functions/const_functions_switch_statements_error_test.dart
@@ -0,0 +1,43 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Tests erroneous switch statements for const functions.
+
+// SharedOptions=--enable-experiment=const-functions
+
+import "package:expect/expect.dart";
+
+const var1 = labelDoesNotExistSwitch(1);
+// ^^^^^^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+int labelDoesNotExistSwitch(int x) {
+ switch (x) {
+ labelOtherSwitch:
+ case 1:
+ break;
+ }
+ switch (x) {
+ case 1:
+ continue labelOtherSwitch;
+// ^
+// [cfe] Can't find label 'labelOtherSwitch'.
+// ^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.LABEL_UNDEFINED
+ }
+ return 0;
+}
+
+const var2 = wrongTypeSwitch(1);
+// ^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+int wrongTypeSwitch(int x) {
+ switch (x) {
+ case "string":
+ // ^^^^^^^^
+ // [analyzer] COMPILE_TIME_ERROR.CASE_EXPRESSION_TYPE_IS_NOT_SWITCH_EXPRESSION_SUBTYPE
+ // [cfe] Type 'String' of the case expression is not a subtype of type 'int' of this switch expression.
+ return 100;
+ }
+ return 0;
+}
diff --git a/tests/language/const_functions/const_functions_switch_statements_test.dart b/tests/language/const_functions/const_functions_switch_statements_test.dart
new file mode 100644
index 0000000..dd1e5c1
--- /dev/null
+++ b/tests/language/const_functions/const_functions_switch_statements_test.dart
@@ -0,0 +1,85 @@
+// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+// Tests switch statements for const functions.
+
+// SharedOptions=--enable-experiment=const-functions
+
+import "package:expect/expect.dart";
+
+const var1 = basicSwitch(1);
+// ^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var2 = basicSwitch(2);
+// ^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+int basicSwitch(int x) {
+ switch (x) {
+ case 1:
+ return 100;
+ default:
+ x++;
+ break;
+ }
+ return x;
+}
+
+const var3 = multipleCaseSwitch(1);
+// ^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var4 = multipleCaseSwitch(2);
+// ^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var5 = multipleCaseSwitch(3);
+// ^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+int multipleCaseSwitch(int x) {
+ switch (x) {
+ case 1:
+ case 2:
+ return 100;
+ default:
+ break;
+ }
+ return 0;
+}
+
+const var6 = continueLabelSwitch(1);
+// ^^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var7 = continueLabelSwitch(2);
+// ^^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var8 = continueLabelSwitch(3);
+// ^^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+const var9 = continueLabelSwitch(4);
+// ^^^^^^^^^^^^^^^^^^^^^^
+// [analyzer] COMPILE_TIME_ERROR.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE
+int continueLabelSwitch(int x) {
+ switch (x) {
+ label1:
+ case 1:
+ x = x + 100;
+ continue label3;
+ case 2:
+ continue label1;
+ label3:
+ case 3:
+ return x + 3;
+ }
+ return 0;
+}
+
+void main() {
+ Expect.equals(var1, 100);
+ Expect.equals(var2, 3);
+ Expect.equals(var3, 100);
+ Expect.equals(var4, 100);
+ Expect.equals(var5, 0);
+ Expect.equals(var6, 104);
+ Expect.equals(var7, 105);
+ Expect.equals(var8, 6);
+ Expect.equals(var9, 0);
+}
diff --git a/tools/VERSION b/tools/VERSION
index 39fe5a8..52a4a09 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
MAJOR 2
MINOR 13
PATCH 0
-PRERELEASE 177
+PRERELEASE 178
PRERELEASE_PATCH 0
\ No newline at end of file