Version 2.10.0-5.0.dev
Merge commit '9d279d41e3677a94bf75f6efb8d5cd98cadd1c7b' into 'dev'
diff --git a/.dart_tool/package_config.json b/.dart_tool/package_config.json
index 57c4b70..706d694 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": "2020-07-14T07:50:57.318843",
+ "generated": "2020-08-07T16:47:24.963156",
"generator": "tools/generate_package_config.dart",
"packages": [
{
@@ -21,6 +21,41 @@
"languageVersion": "2.2"
},
{
+ "name": "_fe_analyzer_shared_assigned_variables",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/assigned_variables",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_definite_assignment",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/definite_assignment",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_definite_unassignment",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/definite_unassignment",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_inheritance",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/inheritance",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_nullability",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/nullability",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_reachability",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/reachability",
+ "packageUri": ".nonexisting/"
+ },
+ {
+ "name": "_fe_analyzer_shared_type_promotion",
+ "rootUri": "../pkg/_fe_analyzer_shared/test/flow_analysis/type_promotion",
+ "packageUri": ".nonexisting/"
+ },
+ {
"name": "_js_interop_checks",
"rootUri": "../pkg/_js_interop_checks",
"packageUri": "lib/",
@@ -48,7 +83,7 @@
"name": "analyzer",
"rootUri": "../pkg/analyzer",
"packageUri": "lib/",
- "languageVersion": "2.6"
+ "languageVersion": "2.7"
},
{
"name": "analyzer_cli",
@@ -107,7 +142,7 @@
"name": "charcode",
"rootUri": "../third_party/pkg/charcode",
"packageUri": "lib/",
- "languageVersion": "2.10"
+ "languageVersion": "2.9"
},
{
"name": "cli_util",
@@ -131,7 +166,7 @@
"name": "convert",
"rootUri": "../third_party/pkg/convert",
"packageUri": "lib/",
- "languageVersion": "2.0"
+ "languageVersion": "2.10"
},
{
"name": "crypto",
@@ -356,7 +391,6 @@
{
"name": "language_versioning_2.7_test",
"rootUri": "../pkg/language_versioning_2.7_test",
- "packageUri": "lib/",
"languageVersion": "2.7"
},
{
@@ -375,7 +409,7 @@
"name": "markdown",
"rootUri": "../third_party/pkg/markdown",
"packageUri": "lib/",
- "languageVersion": "2.2"
+ "languageVersion": "2.6"
},
{
"name": "matcher",
@@ -566,7 +600,7 @@
"name": "sse",
"rootUri": "../third_party/pkg/sse",
"packageUri": "lib/",
- "languageVersion": "2.6"
+ "languageVersion": "2.2"
},
{
"name": "stack_trace",
@@ -602,7 +636,7 @@
"name": "sync_http",
"rootUri": "../third_party/pkg/sync_http",
"packageUri": "lib/",
- "languageVersion": "2.6"
+ "languageVersion": "2.0"
},
{
"name": "telemetry",
@@ -713,12 +747,6 @@
"languageVersion": "2.2"
},
{
- "name": "webdriver",
- "rootUri": "../third_party/pkg/webdriver",
- "packageUri": "lib/",
- "languageVersion": "2.6"
- },
- {
"name": "web_components",
"rootUri": "../third_party/pkg/web_components",
"packageUri": "lib/",
@@ -731,10 +759,16 @@
"languageVersion": "2.0"
},
{
+ "name": "webdriver",
+ "rootUri": "../third_party/pkg/webdriver",
+ "packageUri": "lib/",
+ "languageVersion": "2.0"
+ },
+ {
"name": "yaml",
"rootUri": "../third_party/pkg/yaml",
"packageUri": "lib/",
"languageVersion": "2.4"
}
]
-}
+}
\ No newline at end of file
diff --git a/BUILD.gn b/BUILD.gn
index fe0376d..d59ce8e 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -163,22 +163,30 @@
manifest = "build/fuchsia/dart.cmx"
resource_files = [
- ".packages",
+ ".dart_tool/package_config.json",
"pkg/testing/test/hello_test.dart",
+ "tools/addlatexhash.dart",
]
resource_dirs = [
- "tests/standalone",
- "tests/language_2",
+ "tests/standalone_2",
"pkg/async_helper",
"pkg/expect",
"pkg/meta",
+ "pkg/native_stack_traces",
"pkg/smith",
"third_party/pkg/args",
"third_party/pkg/async",
+ "third_party/pkg/charcode",
"third_party/pkg/collection",
+ "third_party/pkg/convert",
+ "third_party/pkg/crypto",
+ "third_party/pkg/http",
+ "third_party/pkg/http_parser",
"third_party/pkg/path",
"third_party/pkg/pool",
"third_party/pkg/stack_trace",
+ "third_party/pkg/string_scanner",
+ "third_party/pkg/typed_data",
]
resources = []
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54a5a2f..a03d376 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,23 @@
* Introduces `Dart_FinalizableHandle`s. They do auto-delete, and the weakly
referred object cannot be accessed through them.
+### Tools
+
+#### Linter
+
+Updated the Linter to `0.1.118`, which includes:
+
+* New lint: `unnecessary_nullable_for_final_variable_declarations`.
+* Fixed NPE in `prefer_asserts_in_initializer_lists`.
+* Fixed range error in `unnecessary_string_escapes`.
+* `unsafe_html` updated to support unique error codes.
+* Updates to `diagnostic_describe_all_properties` to check for `Diagnosticable`s (not `DiagnosticableMixin`s).
+* New lint: `use_late`.
+* Fixed `unnecessary_lambdas` to respect deferred imports.
+* Updated `public_member_api_docs` to check mixins.
+* Updated `unnecessary_statements` to skip `as` expressions.
+* Fixed `prefer_relative_imports` to work with path dependencies.
+
## 2.9.0 - 2020-08-05
### Language
diff --git a/DEPS b/DEPS
index 042e77d..e03a4be 100644
--- a/DEPS
+++ b/DEPS
@@ -39,16 +39,16 @@
# Checked-in SDK version. The checked-in SDK is a Dart SDK distribution in a
# cipd package used to run Dart scripts in the build and test infrastructure.
- "sdk_tag": "version:2.10.0-0.0.dev",
+ "sdk_tag": "version:2.10.0-3.0.dev",
# co19 is a cipd package. Use update.sh in tests/co19[_2] to update these
# hashes. It requires access to the dart-build-access group, which EngProd
# has.
- "co19_rev": "a9bd47e85862b4af9006c24ea0cb626850bc5de7",
+ "co19_rev": "74eec903ea06fa09dc8799b0552d55b581a82996",
"co19_2_rev": "e48b3090826cf40b8037648f19d211e8eab1b4b6",
# The internal benchmarks to use. See go/dart-benchmarks-internal
- "benchmarks_internal_rev": "1682e8c568cf1899a6da6b5993f0506949253b22",
+ "benchmarks_internal_rev": "991d4cb32af0e914763ebbdeced91395bed874d8",
"checkout_benchmarks_internal": False,
# As Flutter does, we use Fuchsia's GN and Clang toolchain. These revision
@@ -75,9 +75,9 @@
"browser-compat-data_tag": "v1.0.22",
"charcode_rev": "af1e2d59a9c383da94f99ea51dac4b93fb0626c4",
"chrome_rev" : "19997",
- "cli_util_tag" : "0.1.4",
+ "cli_util_tag" : "0.2.0",
"collection_rev": "583693680fc067e34ca5b72503df25e8b80579f9",
- "convert_rev": "49bde5b371eb5c2c8e721557cf762f17c75e49fc",
+ "convert_rev": "c1b01f832835d3d8a06b0b246a361c0eaab35d3c",
"crypto_rev": "7422fb2f6584fe1839eb30bc4ca56e9f9760b801",
"csslib_rev": "451448a9ac03f87a8d0377fc0b411d8c388a6cb4",
"dart2js_info_tag" : "0.6.0",
@@ -113,7 +113,7 @@
"intl_tag": "0.16.1",
"jinja2_rev": "2222b31554f03e62600cd7e383376a7c187967a1",
"json_rpc_2_rev": "d589e635d8ccb7cda6a804bd571f88abbabab146",
- "linter_tag": "0.1.117",
+ "linter_tag": "0.1.118",
"logging_rev": "9561ba016ae607747ae69b846c0e10958ca58ed4",
"markupsafe_rev": "8f45f5cfa0009d2a70589bcda0349b8cb2b72783",
"markdown_rev": "acaddfe74217f62498b5cf0cf5429efa6a700be3",
@@ -677,12 +677,6 @@
'pattern': '.',
'action': ['python', 'sdk/build/vs_toolchain.py', 'update'],
},
- {
- # Download dill files for all supported ABI versions, if necessary.
- 'name': 'abiversions',
- 'pattern': '.',
- 'action': ['python', 'sdk/tools/download_abi_dills.py'],
- },
]
hooks_os = {
diff --git a/benchmarks/IsolateSpawn/dart/helloworld.dart b/benchmarks/IsolateSpawn/dart/helloworld.dart
index 8977e0f..01af7fa 100644
--- a/benchmarks/IsolateSpawn/dart/helloworld.dart
+++ b/benchmarks/IsolateSpawn/dart/helloworld.dart
@@ -1,3 +1,3 @@
-main() {
+void main() {
print('Hello, world!');
}
diff --git a/benchmarks/IsolateSpawn/dart2/helloworld.dart b/benchmarks/IsolateSpawn/dart2/helloworld.dart
index 8977e0f..01af7fa 100644
--- a/benchmarks/IsolateSpawn/dart2/helloworld.dart
+++ b/benchmarks/IsolateSpawn/dart2/helloworld.dart
@@ -1,3 +1,3 @@
-main() {
+void main() {
print('Hello, world!');
}
diff --git a/benchmarks/IsolateSpawnMemory/dart/helloworld.dart b/benchmarks/IsolateSpawnMemory/dart/helloworld.dart
index 8977e0f..01af7fa 100644
--- a/benchmarks/IsolateSpawnMemory/dart/helloworld.dart
+++ b/benchmarks/IsolateSpawnMemory/dart/helloworld.dart
@@ -1,3 +1,3 @@
-main() {
+void main() {
print('Hello, world!');
}
diff --git a/benchmarks/IsolateSpawnMemory/dart2/helloworld.dart b/benchmarks/IsolateSpawnMemory/dart2/helloworld.dart
index 8977e0f..01af7fa 100644
--- a/benchmarks/IsolateSpawnMemory/dart2/helloworld.dart
+++ b/benchmarks/IsolateSpawnMemory/dart2/helloworld.dart
@@ -1,3 +1,3 @@
-main() {
+void main() {
print('Hello, world!');
}
diff --git a/build/fuchsia/dart.cmx b/build/fuchsia/dart.cmx
index b4546c1..f8f5750 100644
--- a/build/fuchsia/dart.cmx
+++ b/build/fuchsia/dart.cmx
@@ -8,7 +8,8 @@
"deprecated-ambient-replace-as-executable",
"root-ssl-certificates",
"isolated-cache-storage",
- "isolated-persistent-storage"
+ "isolated-persistent-storage",
+ "isolated-temp"
],
"services": [
"fuchsia.deprecatedtimezone.Timezone",
diff --git a/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart b/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
index 531cf04..7ee3d3f 100644
--- a/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
+++ b/pkg/_fe_analyzer_shared/lib/src/messages/codes_generated.dart
@@ -5421,6 +5421,27 @@
tip: r"""Try replacing them with named parameters instead.""");
// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const Code<Null> codeJsInteropEnclosingClassJSAnnotation =
+ messageJsInteropEnclosingClassJSAnnotation;
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const MessageCode messageJsInteropEnclosingClassJSAnnotation = const MessageCode(
+ "JsInteropEnclosingClassJSAnnotation",
+ message:
+ r"""Member has a JS interop annotation but the enclosing class does not.""",
+ tip: r"""Try adding the annotation to the enclosing class.""");
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const Code<Null> codeJsInteropEnclosingClassJSAnnotationContext =
+ messageJsInteropEnclosingClassJSAnnotationContext;
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
+const MessageCode messageJsInteropEnclosingClassJSAnnotationContext =
+ const MessageCode("JsInteropEnclosingClassJSAnnotationContext",
+ severity: Severity.context,
+ message: r"""This is the enclosing class.""");
+
+// DO NOT EDIT. THIS FILE IS GENERATED. SEE TOP OF FILE.
const Code<Null> codeJsInteropIndexNotSupported =
messageJsInteropIndexNotSupported;
diff --git a/pkg/_js_interop_checks/lib/js_interop_checks.dart b/pkg/_js_interop_checks/lib/js_interop_checks.dart
index 08cbb83..2355b50 100644
--- a/pkg/_js_interop_checks/lib/js_interop_checks.dart
+++ b/pkg/_js_interop_checks/lib/js_interop_checks.dart
@@ -9,6 +9,8 @@
Message,
LocatedMessage,
messageJsInteropAnonymousFactoryPositionalParameters,
+ messageJsInteropEnclosingClassJSAnnotation,
+ messageJsInteropEnclosingClassJSAnnotationContext,
messageJsInteropIndexNotSupported,
messageJsInteropNamedParameters,
messageJsInteropNonExternalConstructor;
@@ -21,7 +23,15 @@
JsInteropChecks(this._diagnosticsReporter);
@override
+ void defaultMember(Member member) {
+ _checkMemberJSInteropAnnotation(member);
+ super.defaultMember(member);
+ }
+
+ @override
void visitProcedure(Procedure procedure) {
+ _checkMemberJSInteropAnnotation(procedure);
+
if (!procedure.isExternal || !isJSInteropMember(procedure)) return;
if (!procedure.isStatic &&
@@ -55,6 +65,8 @@
@override
void visitConstructor(Constructor constructor) {
+ _checkMemberJSInteropAnnotation(constructor);
+
if (!isJSInteropMember(constructor)) return;
if (!constructor.isExternal && !constructor.isSynthetic) {
@@ -79,4 +91,21 @@
firstNamedParam.location.file);
}
}
+
+ /// Reports an error if [m] has a JS interop annotation and is part of a class
+ /// that does not.
+ void _checkMemberJSInteropAnnotation(Member m) {
+ if (!hasJSInteropAnnotation(m)) return;
+ var enclosingClass = m.enclosingClass;
+ if (enclosingClass != null && !hasJSInteropAnnotation(enclosingClass)) {
+ _diagnosticsReporter.report(messageJsInteropEnclosingClassJSAnnotation,
+ m.fileOffset, m.name.name.length, m.location.file,
+ context: <LocatedMessage>[
+ messageJsInteropEnclosingClassJSAnnotationContext.withLocation(
+ enclosingClass.location.file,
+ enclosingClass.fileOffset,
+ enclosingClass.name.length)
+ ]);
+ }
+ }
}
diff --git a/pkg/analysis_server/lib/src/analysis_server.dart b/pkg/analysis_server/lib/src/analysis_server.dart
index a9414fd..c0d5406 100644
--- a/pkg/analysis_server/lib/src/analysis_server.dart
+++ b/pkg/analysis_server/lib/src/analysis_server.dart
@@ -299,14 +299,6 @@
flutterWidgetDescriptions.flush();
}
- /// Read all files, resolve all URIs, and perform required analysis in
- /// all current analysis drivers.
- void reanalyze() {
- for (var driver in driverMap.values) {
- driver.resetUriResolution();
- }
- }
-
/// Send the given [notification] to the client.
void sendNotification(Notification notification) {
channel.sendNotification(notification);
diff --git a/pkg/analysis_server/lib/src/analysis_server_abstract.dart b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
index 966baae..06cc63c 100644
--- a/pkg/analysis_server/lib/src/analysis_server_abstract.dart
+++ b/pkg/analysis_server/lib/src/analysis_server_abstract.dart
@@ -412,6 +412,14 @@
/// given [path] was changed - added, updated, or removed.
void notifyFlutterWidgetDescriptions(String path) {}
+ /// Read all files, resolve all URIs, and perform required analysis in
+ /// all current analysis drivers.
+ void reanalyze() {
+ for (var driver in driverMap.values) {
+ driver.resetUriResolution();
+ }
+ }
+
/// Sends an error notification to the user.
void sendServerErrorNotification(
String message,
diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights.dart b/pkg/analysis_server/lib/src/computer/computer_highlights.dart
index a0d7ff9..3d4a474 100644
--- a/pkg/analysis_server/lib/src/computer/computer_highlights.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_highlights.dart
@@ -474,6 +474,8 @@
@override
void visitFieldDeclaration(FieldDeclaration node) {
+ computer._addRegion_token(
+ node.abstractKeyword, HighlightRegionType.BUILT_IN);
computer._addRegion_token(node.staticKeyword, HighlightRegionType.BUILT_IN);
super.visitFieldDeclaration(node);
}
diff --git a/pkg/analysis_server/lib/src/computer/computer_highlights2.dart b/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
index 4178ea1..ada8fc5 100644
--- a/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_highlights2.dart
@@ -565,6 +565,8 @@
@override
void visitFieldDeclaration(FieldDeclaration node) {
+ computer._addRegion_token(
+ node.abstractKeyword, HighlightRegionType.BUILT_IN);
computer._addRegion_token(node.staticKeyword, HighlightRegionType.BUILT_IN);
super.visitFieldDeclaration(node);
}
diff --git a/pkg/analysis_server/lib/src/lsp/constants.dart b/pkg/analysis_server/lib/src/lsp/constants.dart
index ba91e4b..93bf55a 100644
--- a/pkg/analysis_server/lib/src/lsp/constants.dart
+++ b/pkg/analysis_server/lib/src/lsp/constants.dart
@@ -53,6 +53,7 @@
abstract class CustomMethods {
static const DiagnosticServer = Method('dart/diagnosticServer');
+ static const Reanalyze = Method('dart/reanalyze');
static const PublishClosingLabels =
Method('dart/textDocument/publishClosingLabels');
static const PublishOutline = Method('dart/textDocument/publishOutline');
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_reanalyze.dart b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_reanalyze.dart
new file mode 100644
index 0000000..ad5c1b3
--- /dev/null
+++ b/pkg/analysis_server/lib/src/lsp/handlers/custom/handler_reanalyze.dart
@@ -0,0 +1,26 @@
+// Copyright (c) 2020, 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:async';
+
+import 'package:analysis_server/lsp_protocol/protocol_generated.dart';
+import 'package:analysis_server/lsp_protocol/protocol_special.dart';
+import 'package:analysis_server/src/lsp/constants.dart';
+import 'package:analysis_server/src/lsp/handlers/handlers.dart';
+import 'package:analysis_server/src/lsp/lsp_analysis_server.dart';
+
+class ReanalyzeHandler extends MessageHandler<void, void> {
+ ReanalyzeHandler(LspAnalysisServer server) : super(server);
+ @override
+ Method get handlesMessage => CustomMethods.Reanalyze;
+
+ @override
+ LspJsonHandler<void> get jsonHandler => NullJsonHandler;
+
+ @override
+ Future<ErrorOr<void>> handle(void _, CancellationToken token) async {
+ server.reanalyze();
+ return success();
+ }
+}
diff --git a/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart b/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
index 48c5ec010..acecc86 100644
--- a/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
+++ b/pkg/analysis_server/lib/src/lsp/handlers/handler_states.dart
@@ -8,6 +8,7 @@
import 'package:analysis_server/lsp_protocol/protocol_special.dart';
import 'package:analysis_server/src/lsp/constants.dart';
import 'package:analysis_server/src/lsp/handlers/custom/handler_diagnostic_server.dart';
+import 'package:analysis_server/src/lsp/handlers/custom/handler_reanalyze.dart';
import 'package:analysis_server/src/lsp/handlers/custom/handler_super.dart';
import 'package:analysis_server/src/lsp/handlers/handler_change_workspace_folders.dart';
import 'package:analysis_server/src/lsp/handlers/handler_code_actions.dart';
@@ -102,6 +103,7 @@
registerHandler(DiagnosticServerHandler(server));
registerHandler(WorkspaceSymbolHandler(server));
registerHandler(WorkspaceDidChangeConfigurationMessageHandler(server));
+ registerHandler(ReanalyzeHandler(server));
}
}
diff --git a/pkg/analysis_server/lib/src/server/driver.dart b/pkg/analysis_server/lib/src/server/driver.dart
index d4ce68a1..44939fc 100644
--- a/pkg/analysis_server/lib/src/server/driver.dart
+++ b/pkg/analysis_server/lib/src/server/driver.dart
@@ -349,7 +349,12 @@
analysisServerOptions.configurationOverrides = sdkConfig;
// ML model configuration.
- final bool enableCompletionModel = results[ENABLE_COMPLETION_MODEL];
+ // TODO(brianwilkerson) Uncomment the line below and delete the second line
+ // when there is a new completion model to query. Until then we ignore the
+ // flag to enable the model so that we can't try to read from a file that
+ // doesn't exist.
+// final bool enableCompletionModel = results[ENABLE_COMPLETION_MODEL];
+ final enableCompletionModel = false;
analysisServerOptions.completionModelFolder =
results[COMPLETION_MODEL_FOLDER];
if (results.wasParsed(ENABLE_COMPLETION_MODEL) && !enableCompletionModel) {
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/keyword_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/keyword_contributor.dart
index fa4ff8f..0e66786 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/keyword_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/keyword_contributor.dart
@@ -306,6 +306,9 @@
if (variables.isEmpty || request.offset > variables.first.beginToken.end) {
return;
}
+ if (node.abstractKeyword == null) {
+ _addSuggestion(Keyword.ABSTRACT);
+ }
if (node.covariantKeyword == null) {
_addSuggestion(Keyword.COVARIANT);
}
diff --git a/pkg/analysis_server/lib/src/services/correction/assist.dart b/pkg/analysis_server/lib/src/services/correction/assist.dart
index 88f78e0..50910b8 100644
--- a/pkg/analysis_server/lib/src/services/correction/assist.dart
+++ b/pkg/analysis_server/lib/src/services/correction/assist.dart
@@ -149,6 +149,8 @@
AssistKind('dart.assist.flutter.wrap.padding', 32, 'Wrap with Padding');
static const FLUTTER_WRAP_ROW =
AssistKind('dart.assist.flutter.wrap.row', 32, 'Wrap with Row');
+ static const FLUTTER_WRAP_SIZED_BOX =
+ AssistKind('dart.assist.flutter.wrap.sizedBox', 32, 'Wrap with SizedBox');
static const FLUTTER_WRAP_STREAM_BUILDER = AssistKind(
'dart.assist.flutter.wrap.streamBuilder', 32, 'Wrap with StreamBuilder');
diff --git a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
index f1c93bf..ce9d943 100644
--- a/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
+++ b/pkg/analysis_server/lib/src/services/correction/bulk_fix_processor.dart
@@ -24,7 +24,9 @@
import 'package:analysis_server/src/services/correction/dart/remove_empty_else.dart';
import 'package:analysis_server/src/services/correction/dart/remove_empty_statement.dart';
import 'package:analysis_server/src/services/correction/dart/remove_initializer.dart';
+import 'package:analysis_server/src/services/correction/dart/remove_method_declaration.dart';
import 'package:analysis_server/src/services/correction/dart/remove_operator.dart';
+import 'package:analysis_server/src/services/correction/dart/remove_this_expression.dart';
import 'package:analysis_server/src/services/correction/dart/remove_type_annotation.dart';
import 'package:analysis_server/src/services/correction/dart/remove_unnecessary_new.dart';
import 'package:analysis_server/src/services/correction/dart/replace_cascade_with_dot.dart';
@@ -32,6 +34,7 @@
import 'package:analysis_server/src/services/correction/dart/replace_null_with_closure.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_conditional_assignment.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_is_empty.dart';
+import 'package:analysis_server/src/services/correction/dart/replace_with_tear_off.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_var.dart';
import 'package:analysis_server/src/services/correction/dart/use_curly_braces.dart';
import 'package:analysis_server/src/services/correction/dart/use_is_not_empty.dart';
@@ -82,8 +85,12 @@
LintNames.prefer_single_quotes: ConvertToSingleQuotes.newInstance,
LintNames.prefer_spread_collections: ConvertAddAllToSpread.newInstance,
LintNames.slash_for_doc_comments: ConvertDocumentationIntoLine.newInstance,
+ LintNames.type_init_formals: RemoveTypeAnnotation.newInstance,
LintNames.unnecessary_const: RemoveUnnecessaryConst.newInstance,
+ LintNames.unnecessary_lambdas: ReplaceWithTearOff.newInstance,
LintNames.unnecessary_new: RemoveUnnecessaryNew.newInstance,
+ LintNames.unnecessary_overrides: RemoveMethodDeclaration.newInstance,
+ LintNames.unnecessary_this: RemoveThisExpression.newInstance,
};
/// A map from an error code to a generator used to create the correction
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/abstract_producer.dart b/pkg/analysis_server/lib/src/services/correction/dart/abstract_producer.dart
index 8b24ec7..cb91e3b 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/abstract_producer.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/abstract_producer.dart
@@ -383,6 +383,11 @@
_context = context;
}
+ /// Return the text that should be displayed to users when referring to the
+ /// given [type].
+ String displayStringForType(DartType type) => type.getDisplayString(
+ withNullability: libraryElement.isNonNullableByDefault);
+
/// Return the function body of the most deeply nested method or function that
/// encloses the [node], or `null` if the node is not in a method or function.
FunctionBody getEnclosingFunctionBody() {
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_enum_case_clauses.dart b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_enum_case_clauses.dart
index 77d58d78..d4426a0 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/add_missing_enum_case_clauses.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/add_missing_enum_case_clauses.dart
@@ -16,7 +16,11 @@
@override
Future<void> compute(ChangeBuilder builder) async {
+ if (node is! SwitchStatement) {
+ return;
+ }
var statement = node as SwitchStatement;
+
String enumName;
var enumConstantNames = <String>[];
var expressionType = statement.expression.staticType;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/change_type_annotation.dart b/pkg/analysis_server/lib/src/services/correction/dart/change_type_annotation.dart
index 480f825..0dfea8a 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/change_type_annotation.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/change_type_annotation.dart
@@ -34,9 +34,8 @@
Expression initializer = coveredNode;
var newType = initializer.staticType;
if (newType is InterfaceType || newType is FunctionType) {
- _oldAnnotation =
- typeNode.type.getDisplayString(withNullability: false);
- _newAnnotation = newType.getDisplayString(withNullability: false);
+ _oldAnnotation = displayStringForType(typeNode.type);
+ _newAnnotation = displayStringForType(newType);
await builder.addDartFileEdit(file, (builder) {
builder.addReplacement(range.node(typeNode), (builder) {
builder.writeType(newType);
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap.dart b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap.dart
index 389ad42..c8c935b 100644
--- a/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap.dart
+++ b/pkg/analysis_server/lib/src/services/correction/dart/flutter_wrap.dart
@@ -29,6 +29,9 @@
if (!flutter.isExactWidgetTypePadding(widgetType)) {
yield _FlutterWrapPadding(widgetExpr);
}
+ if (!flutter.isExactWidgetTypeSizedBox(widgetType)) {
+ yield _FlutterWrapSizedBox(widgetExpr);
+ }
}
yield* _wrapMultipleWidgets();
}
@@ -167,6 +170,21 @@
/// A correction processor that can make one of the possible change computed by
/// the [FlutterWrap] producer.
+class _FlutterWrapSizedBox extends _WrapSingleWidget {
+ _FlutterWrapSizedBox(Expression widgetExpr) : super(widgetExpr);
+
+ @override
+ AssistKind get assistKind => DartAssistKind.FLUTTER_WRAP_SIZED_BOX;
+
+ @override
+ String get _parentClassName => 'SizedBox';
+
+ @override
+ String get _parentLibraryUri => flutter.widgetsUri;
+}
+
+/// A correction processor that can make one of the possible change computed by
+/// the [FlutterWrap] producer.
abstract class _WrapMultipleWidgets extends CorrectionProducer {
final Expression firstWidget;
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/make_return_type_nullable.dart b/pkg/analysis_server/lib/src/services/correction/dart/make_return_type_nullable.dart
new file mode 100644
index 0000000..5fdea07
--- /dev/null
+++ b/pkg/analysis_server/lib/src/services/correction/dart/make_return_type_nullable.dart
@@ -0,0 +1,63 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/correction/dart/abstract_producer.dart';
+import 'package:analysis_server/src/services/correction/fix.dart';
+import 'package:analyzer/dart/analysis/features.dart';
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+
+class MakeReturnTypeNullable extends CorrectionProducer {
+ @override
+ FixKind get fixKind => DartFixKind.MAKE_RETURN_TYPE_NULLABLE;
+
+ @override
+ Future<void> compute(ChangeBuilder builder) async {
+ if (!unit.featureSet.isEnabled(Feature.non_nullable)) {
+ return;
+ }
+ if (node is! Expression) {
+ return;
+ }
+ var body = node.thisOrAncestorOfType<FunctionBody>();
+ TypeAnnotation returnType;
+ var function = body.parent;
+ if (function is FunctionExpression) {
+ function = function.parent;
+ }
+ if (function is MethodDeclaration) {
+ returnType = function.returnType;
+ } else if (function is FunctionDeclaration) {
+ returnType = function.returnType;
+ } else {
+ return;
+ }
+ if (body.isAsynchronous || body.isGenerator) {
+ if (returnType is! NamedType) {
+ return null;
+ }
+ var typeArguments = (returnType as NamedType).typeArguments;
+ if (typeArguments == null) {
+ return null;
+ }
+ var arguments = typeArguments.arguments;
+ if (arguments.length != 1) {
+ return null;
+ }
+ returnType = arguments[0];
+ }
+ if (node is! NullLiteral &&
+ !typeSystem.isAssignableTo(returnType.type,
+ typeSystem.promoteToNonNull((node as Expression).staticType))) {
+ return;
+ }
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addSimpleInsertion(returnType.end, '?');
+ });
+ }
+
+ /// Return an instance of this class. Used as a tear-off in `FixProcessor`.
+ static MakeReturnTypeNullable newInstance() => MakeReturnTypeNullable();
+}
diff --git a/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart
new file mode 100644
index 0000000..75d20bcb
--- /dev/null
+++ b/pkg/analysis_server/lib/src/services/correction/dart/replace_with_not_null_aware.dart
@@ -0,0 +1,61 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/correction/dart/abstract_producer.dart';
+import 'package:analysis_server/src/services/correction/fix.dart';
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:analyzer_plugin/utilities/range_factory.dart';
+
+class ReplaceWithNotNullAware extends CorrectionProducer {
+ /// The operator that will replace the existing operator.
+ String _newOperator;
+
+ @override
+ List<Object> get fixArguments => [_newOperator];
+
+ @override
+ FixKind get fixKind => DartFixKind.REPLACE_WITH_NOT_NULL_AWARE;
+
+ @override
+ Future<void> compute(ChangeBuilder builder) async {
+ var node = coveredNode;
+ if (node is MethodInvocation) {
+ _newOperator =
+ node.operator.type == TokenType.QUESTION_PERIOD ? '.' : '..';
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addSimpleReplacement(range.token(node.operator), _newOperator);
+ });
+ } else if (node is PropertyAccess) {
+ _newOperator =
+ node.operator.type == TokenType.QUESTION_PERIOD ? '.' : '..';
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addSimpleReplacement(range.token(node.operator), _newOperator);
+ });
+ } else if (node is IndexExpression) {
+ if (node.period != null) {
+ _newOperator = '..';
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addSimpleReplacement(range.token(node.period), '..');
+ });
+ } else if (node.question != null) {
+ _newOperator = '[';
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addDeletion(range.token(node.question));
+ });
+ }
+ } else if (node is SpreadElement) {
+ _newOperator = '...';
+ await builder.addDartFileEdit(file, (builder) {
+ builder.addSimpleReplacement(
+ range.token(node.spreadOperator), _newOperator);
+ });
+ }
+ }
+
+ /// Return an instance of this class. Used as a tear-off in `FixProcessor`.
+ static ReplaceWithNotNullAware newInstance() => ReplaceWithNotNullAware();
+}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix.dart b/pkg/analysis_server/lib/src/services/correction/fix.dart
index 83b5c92..0f67130 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix.dart
@@ -315,6 +315,8 @@
static const MAKE_FIELD_NOT_FINAL =
FixKind('dart.fix.makeFieldNotFinal', 50, "Make field '{0}' not final");
static const MAKE_FINAL = FixKind('dart.fix.makeFinal', 50, 'Make final');
+ static const MAKE_RETURN_TYPE_NULLABLE = FixKind(
+ 'dart.fix.makeReturnTypeNullable', 50, 'Make the return type nullable');
static const MOVE_TYPE_ARGUMENTS_TO_CLASS = FixKind(
'dart.fix.moveTypeArgumentsToClass',
50,
@@ -446,6 +448,8 @@
FixKind('dart.fix.replace.withIsEmpty', 50, "Replace with 'isEmpty'");
static const REPLACE_WITH_IS_NOT_EMPTY = FixKind(
'dart.fix.replace.withIsNotEmpty', 50, "Replace with 'isNotEmpty'");
+ static const REPLACE_WITH_NOT_NULL_AWARE =
+ FixKind('dart.fix.replace.withNotNullAware', 50, "Replace with '{0}'");
static const REPLACE_WITH_NULL_AWARE = FixKind(
'dart.fix.replace.withNullAware',
50,
diff --git a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
index 17d2049..ec4ab2e 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
@@ -79,6 +79,7 @@
import 'package:analysis_server/src/services/correction/dart/make_class_abstract.dart';
import 'package:analysis_server/src/services/correction/dart/make_field_not_final.dart';
import 'package:analysis_server/src/services/correction/dart/make_final.dart';
+import 'package:analysis_server/src/services/correction/dart/make_return_type_nullable.dart';
import 'package:analysis_server/src/services/correction/dart/make_variable_not_final.dart';
import 'package:analysis_server/src/services/correction/dart/move_type_arguments_to_class.dart';
import 'package:analysis_server/src/services/correction/dart/organize_imports.dart';
@@ -132,6 +133,7 @@
import 'package:analysis_server/src/services/correction/dart/replace_with_identifier.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_interpolation.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_is_empty.dart';
+import 'package:analysis_server/src/services/correction/dart/replace_with_not_null_aware.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_null_aware.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_tear_off.dart';
import 'package:analysis_server/src/services/correction/dart/replace_with_var.dart';
@@ -750,6 +752,12 @@
CompileTimeErrorCode.NULLABLE_TYPE_IN_WITH_CLAUSE: [
RemoveQuestionMark.newInstance,
],
+ CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_FUNCTION: [
+ MakeReturnTypeNullable.newInstance,
+ ],
+ CompileTimeErrorCode.RETURN_OF_INVALID_TYPE_FROM_METHOD: [
+ MakeReturnTypeNullable.newInstance,
+ ],
CompileTimeErrorCode.TYPE_TEST_WITH_UNDEFINED_NAME: [
ChangeTo.classOrMixin,
CreateClass.newInstance,
@@ -842,6 +850,9 @@
MoveTypeArgumentsToClass.newInstance,
RemoveTypeArguments.newInstance,
],
+ CompileTimeErrorCode.YIELD_OF_INVALID_TYPE: [
+ MakeReturnTypeNullable.newInstance,
+ ],
HintCode.CAN_BE_NULL_AFTER_NULL_AWARE: [
ReplaceWithNullAware.newInstance,
@@ -1004,6 +1015,9 @@
StaticWarningCode.DEAD_NULL_AWARE_EXPRESSION: [
RemoveDeadIfNull.newInstance,
],
+ StaticWarningCode.INVALID_NULL_AWARE_OPERATOR: [
+ ReplaceWithNotNullAware.newInstance,
+ ],
StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH: [
AddMissingEnumCaseClauses.newInstance,
],
diff --git a/pkg/analysis_server/lib/src/utilities/flutter.dart b/pkg/analysis_server/lib/src/utilities/flutter.dart
index c7f167f..d5a48c5 100644
--- a/pkg/analysis_server/lib/src/utilities/flutter.dart
+++ b/pkg/analysis_server/lib/src/utilities/flutter.dart
@@ -16,6 +16,7 @@
static const _nameCenter = 'Center';
static const _nameContainer = 'Container';
static const _namePadding = 'Padding';
+ static const _nameSizedBox = 'SizedBox';
static const _nameState = 'State';
static const _nameStatefulWidget = 'StatefulWidget';
static const _nameStatelessWidget = 'StatelessWidget';
@@ -450,6 +451,12 @@
_isExactWidget(type.element, _namePadding, _uriBasic);
}
+ /// Return `true` if the given [type] is the Flutter class `SizedBox`.
+ bool isExactWidgetTypeSizedBox(DartType type) {
+ return type is InterfaceType &&
+ _isExactWidget(type.element, _nameSizedBox, _uriBasic);
+ }
+
/// Return `true` if the given [type] is the Flutter class `StreamBuilder`.
bool isExactWidgetTypeStreamBuilder(DartType type) {
return type is InterfaceType &&
diff --git a/pkg/analysis_server/test/lsp/reanalyze_test.dart b/pkg/analysis_server/test/lsp/reanalyze_test.dart
new file mode 100644
index 0000000..69afce8
--- /dev/null
+++ b/pkg/analysis_server/test/lsp/reanalyze_test.dart
@@ -0,0 +1,38 @@
+// Copyright (c) 2020, 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:analysis_server/lsp_protocol/protocol_generated.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'server_abstract.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(ReanalyzeTest);
+ });
+}
+
+@reflectiveTest
+class ReanalyzeTest extends AbstractLspAnalysisServerTest {
+ Future<void> test_reanalyze() async {
+ const initialContents = 'int a = 1;';
+ newFile(mainFilePath, content: initialContents);
+
+ final initialAnalysis = waitForAnalysisComplete();
+
+ await initialize();
+ await initialAnalysis;
+
+ // Set up futures to wait for the new events.
+ final startNotification = waitForAnalysisStart();
+ final completeNotification = waitForAnalysisComplete();
+
+ final request = makeRequest(Method.fromJson(r'dart/reanalyze'), null);
+ await channel.sendRequestToServer(request);
+
+ // Ensure the notifications come through again.
+ await startNotification;
+ await completeNotification;
+ }
+}
diff --git a/pkg/analysis_server/test/lsp/test_all.dart b/pkg/analysis_server/test/lsp/test_all.dart
index 0870436..628b142 100644
--- a/pkg/analysis_server/test/lsp/test_all.dart
+++ b/pkg/analysis_server/test/lsp/test_all.dart
@@ -30,6 +30,7 @@
import 'mapping_test.dart' as mapping;
import 'outline_test.dart' as outline;
import 'priority_files_test.dart' as priority_files;
+import 'reanalyze_test.dart' as reanalyze;
import 'references_test.dart' as references;
import 'rename_test.dart' as rename;
import 'server_test.dart' as server;
@@ -66,6 +67,7 @@
mapping.main();
outline.main();
priority_files.main();
+ reanalyze.main();
references.main();
rename.main();
server.main();
diff --git a/pkg/analysis_server/test/mock_packages/flutter/lib/src/widgets/basic.dart b/pkg/analysis_server/test/mock_packages/flutter/lib/src/widgets/basic.dart
index 761a15c..68ecbc6 100644
--- a/pkg/analysis_server/test/mock_packages/flutter/lib/src/widgets/basic.dart
+++ b/pkg/analysis_server/test/mock_packages/flutter/lib/src/widgets/basic.dart
@@ -65,6 +65,30 @@
const Center({Key key, double heightFactor, Widget child});
}
+class SizedBox extends SingleChildRenderObjectWidget {
+ const SizedBox({Key key, this.width, this.height, Widget child})
+ : super(key: key, child: child);
+
+ const SizedBox.expand({Key key, Widget child})
+ : width = double.infinity,
+ height = double.infinity,
+ super(key: key, child: child);
+
+ const SizedBox.shrink({Key key, Widget child})
+ : width = 0.0,
+ height = 0.0,
+ super(key: key, child: child);
+
+ SizedBox.fromSize({Key key, Widget child, Size size})
+ : width = size?.width,
+ height = size?.height,
+ super(key: key, child: child);
+
+ final double width;
+
+ final double height;
+}
+
class ClipRect extends SingleChildRenderObjectWidget {
const ClipRect({Key key, Widget child}) : super(key: key, child: child);
diff --git a/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
index 203a14c..93e5edc 100644
--- a/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/arglist_contributor_test.dart
@@ -76,7 +76,6 @@
bool includeColon = true,
bool includeComma = false}) {
var expected = <CompletionSuggestion>[];
- var paramIndex = 0;
namedArgumentsWithTypes.forEach((String name, String type) {
var completion = includeColon ? '$name: ' : name;
// Selection should be before any trailing commas.
@@ -84,12 +83,8 @@
if (includeComma) {
completion = '$completion,';
}
- var relevance = requiredParamIndices.contains(paramIndex++)
- ? DART_RELEVANCE_NAMED_PARAMETER_REQUIRED
- : DART_RELEVANCE_NAMED_PARAMETER;
expected.add(assertSuggest(completion,
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: relevance,
paramName: name,
paramType: type,
selectionOffset: selectionOffset));
@@ -106,7 +101,6 @@
suggestion.endsWith(',') ? suggestion.length - 1 : suggestion.length;
expected.add(assertSuggest('$suggestion',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
selectionOffset: selectionOffset));
}
assertNoOtherSuggestions(expected);
@@ -253,7 +247,6 @@
assertSuggest(
'(a, b) => ,',
- relevance: DART_RELEVANCE_HIGH,
selectionOffset: 10,
);
@@ -349,7 +342,6 @@
assertSuggest(
'(a, {b, c}) => ,',
- relevance: DART_RELEVANCE_HIGH,
selectionOffset: 15,
);
}
@@ -382,7 +374,6 @@
assertSuggest(
'(a, [b, c]) => ,',
- relevance: DART_RELEVANCE_HIGH,
selectionOffset: 15,
);
}
@@ -402,7 +393,6 @@
assertSuggest('children: [],',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null,
selectionOffset: 11,
defaultArgumentListTextRanges: null);
@@ -425,7 +415,6 @@
assertSuggest('backgroundColor: ,',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null, // No default values.
selectionOffset: 17);
}
@@ -446,7 +435,6 @@
assertSuggest('children: [],',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null,
selectionOffset: 11,
defaultArgumentListTextRanges: null);
@@ -468,7 +456,6 @@
assertSuggest('children: [],',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null,
selectionOffset: 11,
defaultArgumentListTextRanges: null);
@@ -496,7 +483,6 @@
assertSuggest('children: [],',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null,
selectionOffset: 11,
defaultArgumentListTextRanges: null);
@@ -523,7 +509,6 @@
assertSuggest('children: ,',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
selectionOffset: 10,
defaultArgListString: null);
}
@@ -548,7 +533,6 @@
assertSuggest('slivers: [],',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null,
selectionOffset: 10,
defaultArgumentListTextRanges: null);
@@ -575,7 +559,6 @@
assertSuggest('children: ',
csKind: CompletionSuggestionKind.NAMED_ARGUMENT,
- relevance: DART_RELEVANCE_NAMED_PARAMETER,
defaultArgListString: null);
}
diff --git a/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
index f984fb0..f5faa6a 100644
--- a/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/combinator_contributor_test.dart
@@ -55,15 +55,9 @@
class X {}''');
await computeSuggestions();
- assertSuggestClass('A',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
- assertSuggestClass('B',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
- assertSuggestClass('PB',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('PB', kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestTopLevelVar('T1', null,
kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestFunction('F1', 'PB',
@@ -104,23 +98,15 @@
class X {}''');
await computeSuggestions();
- assertSuggestClass('A',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
- assertSuggestClass('B',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('_AB');
- assertSuggestClass('PB',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('PB', kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestTopLevelVar('T1', null,
kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestFunction('F1', 'PB',
kind: CompletionSuggestionKind.IDENTIFIER);
- assertSuggestClass('Clz',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('Clz', kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestFunctionTypeAlias('F2', null,
kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('C');
@@ -147,9 +133,7 @@
import 'b.dart' show ^;
''');
await computeSuggestions();
- assertSuggestClass('A',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('B');
}
@@ -173,11 +157,7 @@
import "b.dart" show ^;
''');
await computeSuggestions();
- assertSuggestClass('A',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
- assertSuggestClass('B',
- relevance: DART_RELEVANCE_DEFAULT,
- kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('A', kind: CompletionSuggestionKind.IDENTIFIER);
+ assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
}
}
diff --git a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
index 2242171..d326ca1 100644
--- a/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
+++ b/pkg/analysis_server/test/services/completion/dart/completion_contributor_util.dart
@@ -183,7 +183,6 @@
CompletionSuggestion assertSuggest(String completion,
{CompletionSuggestionKind csKind = CompletionSuggestionKind.INVOCATION,
- int relevance,
ElementKind elemKind,
bool isDeprecated = false,
bool isPotential = false,
@@ -202,11 +201,6 @@
failedCompletion('expected $completion $csKind $elemKind', suggestions);
}
expect(cs.kind, equals(csKind));
- // todo (pq): remove when all relevance tests have been migrated
- // see: https://github.com/dart-lang/sdk/issues/40104
- if (relevance != null) {
- expect(cs.relevance, equals(relevance), reason: completion);
- }
expect(cs.selectionOffset, equals(selectionOffset ?? completion.length));
expect(cs.selectionLength, equals(0));
expect(cs.isDeprecated, equals(isDeprecated));
@@ -241,15 +235,13 @@
}
CompletionSuggestion assertSuggestClass(String name,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
String elemFile,
String elemName,
int elemOffset}) {
var cs = assertSuggest(name,
csKind: kind,
- relevance: relevance,
isDeprecated: isDeprecated,
elemFile: elemFile,
elemKind: ElementKind.CLASS,
@@ -265,9 +257,8 @@
}
CompletionSuggestion assertSuggestClassTypeAlias(String name,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
- var cs = assertSuggest(name, csKind: kind, relevance: relevance);
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
+ var cs = assertSuggest(name, csKind: kind);
var element = cs.element;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.CLASS_TYPE_ALIAS));
@@ -279,13 +270,11 @@
}
CompletionSuggestion assertSuggestConstructor(String name,
- {int relevance,
- String elementName,
+ {String elementName,
int elemOffset,
String defaultArgListString = _UNCHECKED,
List<int> defaultArgumentListTextRanges}) {
var cs = assertSuggest(name,
- relevance: relevance,
elemKind: ElementKind.CONSTRUCTOR,
elemOffset: elemOffset,
defaultArgListString: defaultArgListString,
@@ -308,19 +297,8 @@
}
CompletionSuggestion assertSuggestEnumConst(String completion,
- {int relevance = DART_RELEVANCE_DEFAULT,
- bool isDeprecated = false,
- bool hasTypeBoost = false}) {
- // todo (pq): remove when all relevance tests have been migrated
- // see: https://github.com/dart-lang/sdk/issues/40104
- if (isDeprecated) {
- relevance = DART_RELEVANCE_LOW;
- }
- if (hasTypeBoost) {
- relevance += DART_RELEVANCE_BOOST_TYPE;
- }
- var suggestion = assertSuggest(completion,
- relevance: relevance, isDeprecated: isDeprecated);
+ {bool isDeprecated = false}) {
+ var suggestion = assertSuggest(completion, isDeprecated: isDeprecated);
expect(suggestion.completion, completion);
expect(suggestion.isDeprecated, isDeprecated);
expect(suggestion.element.kind, ElementKind.ENUM_CONSTANT);
@@ -328,14 +306,10 @@
}
CompletionSuggestion assertSuggestField(String name, String type,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false}) {
var cs = assertSuggest(name,
- csKind: kind,
- relevance: relevance,
- elemKind: ElementKind.FIELD,
- isDeprecated: isDeprecated);
+ csKind: kind, elemKind: ElementKind.FIELD, isDeprecated: isDeprecated);
// The returnType represents the type of a field
expect(cs.returnType, type ?? 'dynamic');
var element = cs.element;
@@ -352,12 +326,10 @@
CompletionSuggestion assertSuggestFunction(String name, String returnType,
{CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
- int relevance,
String defaultArgListString = _UNCHECKED,
List<int> defaultArgumentListTextRanges}) {
var cs = assertSuggest(name,
csKind: kind,
- relevance: relevance,
isDeprecated: isDeprecated,
defaultArgListString: defaultArgListString,
defaultArgumentListTextRanges: defaultArgumentListTextRanges);
@@ -388,11 +360,9 @@
String name,
String returnType, {
bool isDeprecated = false,
- int relevance,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
}) {
- var cs = assertSuggest(name,
- csKind: kind, relevance: relevance, isDeprecated: isDeprecated);
+ var cs = assertSuggest(name, csKind: kind, isDeprecated: isDeprecated);
if (returnType != null) {
expect(cs.returnType, returnType);
} else if (isNullExpectedReturnTypeConsideredDynamic) {
@@ -417,14 +387,10 @@
}
CompletionSuggestion assertSuggestGetter(String name, String returnType,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false}) {
var cs = assertSuggest(name,
- csKind: kind,
- relevance: relevance,
- elemKind: ElementKind.GETTER,
- isDeprecated: isDeprecated);
+ csKind: kind, elemKind: ElementKind.GETTER, isDeprecated: isDeprecated);
expect(cs.returnType, returnType ?? 'dynamic');
var element = cs.element;
expect(element, isNotNull);
@@ -437,18 +403,9 @@
}
CompletionSuggestion assertSuggestLocalVariable(
- String name, String returnType,
- {int relevance = DART_RELEVANCE_LOCAL_VARIABLE,
- bool hasTypeBoost = false,
- bool hasSubtypeBoost = false}) {
- if (hasTypeBoost) {
- relevance += DART_RELEVANCE_BOOST_TYPE;
- } else if (hasSubtypeBoost) {
- relevance += DART_RELEVANCE_BOOST_SUBTYPE;
- }
+ String name, String returnType) {
// Local variables should only be suggested by LocalReferenceContributor
- var cs = assertSuggest(name,
- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance);
+ var cs = assertSuggest(name, csKind: CompletionSuggestionKind.INVOCATION);
expect(cs.returnType, returnType ?? 'dynamic');
var element = cs.element;
expect(element, isNotNull);
@@ -462,15 +419,13 @@
CompletionSuggestion assertSuggestMethod(
String name, String declaringType, String returnType,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
String defaultArgListString = _UNCHECKED,
List<int> defaultArgumentListTextRanges,
bool skipLocationCheck = false}) {
var cs = assertSuggest(name,
csKind: kind,
- relevance: relevance,
isDeprecated: isDeprecated,
defaultArgListString: defaultArgListString,
defaultArgumentListTextRanges: defaultArgumentListTextRanges,
@@ -491,15 +446,13 @@
}
CompletionSuggestion assertSuggestMixin(String name,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
bool isDeprecated = false,
String elemFile,
String elemName,
int elemOffset}) {
var cs = assertSuggest(name,
csKind: kind,
- relevance: relevance,
isDeprecated: isDeprecated,
elemFile: elemFile,
elemKind: ElementKind.MIXIN,
@@ -515,21 +468,17 @@
}
CompletionSuggestion assertSuggestName(String name,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.IDENTIFIER,
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.IDENTIFIER,
bool isDeprecated = false}) {
- var cs = assertSuggest(name,
- csKind: kind, relevance: relevance, isDeprecated: isDeprecated);
+ var cs = assertSuggest(name, csKind: kind, isDeprecated: isDeprecated);
expect(cs.completion, equals(name));
expect(cs.element, isNull);
assertHasNoParameterInfo(cs);
return cs;
}
- CompletionSuggestion assertSuggestParameter(String name, String returnType,
- {int relevance = DART_RELEVANCE_PARAMETER}) {
- var cs = assertSuggest(name,
- csKind: CompletionSuggestionKind.INVOCATION, relevance: relevance);
+ CompletionSuggestion assertSuggestParameter(String name, String returnType) {
+ var cs = assertSuggest(name, csKind: CompletionSuggestionKind.INVOCATION);
expect(cs.returnType, returnType ?? 'dynamic');
var element = cs.element;
expect(element, isNotNull);
@@ -541,10 +490,8 @@
}
CompletionSuggestion assertSuggestSetter(String name,
- {int relevance,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
- var cs = assertSuggest(name,
- csKind: kind, relevance: relevance, elemKind: ElementKind.SETTER);
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION}) {
+ var cs = assertSuggest(name, csKind: kind, elemKind: ElementKind.SETTER);
var element = cs.element;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.SETTER));
@@ -562,10 +509,9 @@
CompletionSuggestion assertSuggestTopLevelVar(
String name,
String returnType, {
- int relevance,
CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION,
}) {
- var cs = assertSuggest(name, csKind: kind, relevance: relevance);
+ var cs = assertSuggest(name, csKind: kind);
if (returnType != null) {
expect(cs.returnType, returnType);
} else if (isNullExpectedReturnTypeConsideredDynamic) {
@@ -585,10 +531,8 @@
return cs;
}
- CompletionSuggestion assertSuggestTypeParameter(String name,
- {int relevance = DART_RELEVANCE_TYPE_PARAMETER}) {
- var cs = assertSuggest(name,
- csKind: CompletionSuggestionKind.IDENTIFIER, relevance: relevance);
+ CompletionSuggestion assertSuggestTypeParameter(String name) {
+ var cs = assertSuggest(name, csKind: CompletionSuggestionKind.IDENTIFIER);
expect(cs.returnType, isNull);
var element = cs.element;
expect(element, isNotNull);
diff --git a/pkg/analysis_server/test/services/completion/dart/field_formal_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/field_formal_contributor_test.dart
index 9c45414..d28095f 100644
--- a/pkg/analysis_server/test/services/completion/dart/field_formal_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/field_formal_contributor_test.dart
@@ -50,8 +50,8 @@
await computeSuggestions();
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('sb');
assertNotSuggested('d');
assertNotSuggested('_e');
@@ -86,8 +86,8 @@
await computeSuggestions();
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('d');
assertNotSuggested('_e');
assertNotSuggested('f');
@@ -121,8 +121,8 @@
await computeSuggestions();
expect(replacementOffset, completionOffset);
expect(replacementLength, 1);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('d');
assertNotSuggested('_e');
assertNotSuggested('f');
@@ -157,7 +157,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertNotSuggested('b');
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('_c', 'X');
assertNotSuggested('d');
assertNotSuggested('_e');
assertNotSuggested('f');
@@ -186,7 +186,7 @@
await computeSuggestions();
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('y', 'int', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('y', 'int');
assertNotSuggested('x');
}
@@ -202,7 +202,7 @@
await computeSuggestions();
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('y', 'int', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('y', 'int');
assertNotSuggested('x');
}
}
diff --git a/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
index b043bd3..7e7ce51 100644
--- a/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/imported_reference_contributor_test.dart
@@ -1018,8 +1018,7 @@
assertNotSuggested('_B');
// hidden element not suggested
assertNotSuggested('D');
- assertSuggestFunction('D1', 'dynamic',
- isDeprecated: true, relevance: DART_RELEVANCE_LOW);
+ assertSuggestFunction('D1', 'dynamic', isDeprecated: true);
assertNotSuggested('D2');
// Not imported, so not suggested
assertNotSuggested('D3');
@@ -1873,8 +1872,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2769,15 +2768,9 @@
''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
assertSuggestConstructor('D', elemOffset: -1);
}
diff --git a/pkg/analysis_server/test/services/completion/dart/keyword_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/keyword_contributor_test.dart
index 32b6dc8..b651d8a 100644
--- a/pkg/analysis_server/test/services/completion/dart/keyword_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/keyword_contributor_test.dart
@@ -385,7 +385,12 @@
}
List<Keyword> get staticMember {
- var keywords = <Keyword>[Keyword.CONST, Keyword.COVARIANT, Keyword.FINAL];
+ var keywords = <Keyword>[
+ Keyword.ABSTRACT,
+ Keyword.CONST,
+ Keyword.COVARIANT,
+ Keyword.FINAL
+ ];
if (isEnabled(ExperimentalFeatures.non_nullable)) {
keywords.add(Keyword.LATE);
}
@@ -393,8 +398,7 @@
}
void assertSuggestKeywords(Iterable<Keyword> expectedKeywords,
- {List<String> pseudoKeywords = NO_PSEUDO_KEYWORDS,
- int relevance = DART_RELEVANCE_KEYWORD}) {
+ {List<String> pseudoKeywords = NO_PSEUDO_KEYWORDS}) {
var expectedCompletions = <String>{};
var expectedOffsets = <String, int>{};
var actualCompletions = <String>{};
@@ -431,16 +435,6 @@
}
for (var s in suggestions) {
if (s.kind == CompletionSuggestionKind.KEYWORD) {
- if (s.completion.startsWith(Keyword.IMPORT.lexeme)) {
- var importRelevance = relevance;
- expect(s.relevance, equals(importRelevance), reason: s.completion);
- } else {
- if (s.completion == Keyword.RETHROW.lexeme) {
- expect(s.relevance, equals(relevance - 1), reason: s.completion);
- } else {
- expect(s.relevance, equals(relevance), reason: s.completion);
- }
- }
var expectedOffset = expectedOffsets[s.completion];
expectedOffset ??= s.completion.length;
expect(
@@ -467,35 +461,31 @@
Future<void> test_after_class_noPrefix() async {
addTestSource('class A {} ^');
await computeSuggestions();
- assertSuggestKeywords(declarationKeywords, relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(declarationKeywords);
}
Future<void> test_after_class_prefix() async {
addTestSource('class A {} c^');
await computeSuggestions();
- assertSuggestKeywords(declarationKeywords, relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(declarationKeywords);
}
Future<void> test_after_import_noPrefix() async {
addTestSource('import "foo"; ^');
await computeSuggestions();
- assertSuggestKeywords(directiveAndDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveAndDeclarationKeywords);
}
Future<void> test_after_import_prefix() async {
addTestSource('import "foo"; c^');
await computeSuggestions();
- assertSuggestKeywords(directiveAndDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveAndDeclarationKeywords);
}
Future<void> test_anonymous_function_async() async {
addTestSource('main() {foo(() ^ {}}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_anonymous_function_async2() async {
@@ -505,9 +495,7 @@
// and reports a single function expression argument
// while analyzer adds the closing paren before the `a`
// and adds synthetic `;`s making `a` a statement.
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_anonymous_function_async3() async {
@@ -519,8 +507,7 @@
Future<void> test_anonymous_function_async4() async {
addTestSource('main() {foo(() ^ => 2}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async']);
}
Future<void> test_anonymous_function_async5() async {
@@ -533,9 +520,7 @@
Future<void> test_anonymous_function_async6() async {
addTestSource('main() {foo("bar", () as^{}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_anonymous_function_async7() async {
@@ -543,16 +528,13 @@
await computeSuggestions();
assertSuggestKeywords([],
pseudoKeywords:
- usingFastaParser ? ['async'] : ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ usingFastaParser ? ['async'] : ['async', 'async*', 'sync*']);
}
Future<void> test_anonymous_function_async8() async {
addTestSource('main() {foo(() ^ {})}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_anonymous_function_async9() async {
@@ -560,9 +542,7 @@
await computeSuggestions();
// Fasta interprets the argument as a function expression
// while analyzer adds synthetic `;`s making `a` a statement.
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_argument() async {
@@ -643,8 +623,7 @@
addTestSource('^ import foo;');
await computeSuggestions();
assertSuggestKeywords(
- [Keyword.EXPORT, Keyword.IMPORT, Keyword.LIBRARY, Keyword.PART],
- relevance: DART_RELEVANCE_HIGH);
+ [Keyword.EXPORT, Keyword.IMPORT, Keyword.LIBRARY, Keyword.PART]);
}
Future<void> test_catch_1a() async {
@@ -848,8 +827,7 @@
Future<void> test_class() async {
addTestSource('class A e^ { }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_body() async {
@@ -906,22 +884,19 @@
Future<void> test_class_extends() async {
addTestSource('class A extends foo ^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH]);
}
Future<void> test_class_extends2() async {
addTestSource('class A extends foo i^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH]);
}
Future<void> test_class_extends3() async {
addTestSource('class A extends foo i^ { }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS, Keyword.WITH]);
}
Future<void> test_class_extends_name() async {
@@ -933,27 +908,23 @@
Future<void> test_class_implements() async {
addTestSource('class A ^ implements foo');
await computeSuggestions();
- assertSuggestKeywords([Keyword.EXTENDS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.EXTENDS]);
}
Future<void> test_class_implements2() async {
addTestSource('class A e^ implements foo');
await computeSuggestions();
- assertSuggestKeywords(
- usingFastaParser
- ? [Keyword.EXTENDS]
- : [Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(usingFastaParser
+ ? [Keyword.EXTENDS]
+ : [Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_implements3() async {
addTestSource('class A e^ implements foo { }');
await computeSuggestions();
- assertSuggestKeywords(
- usingFastaParser
- ? [Keyword.EXTENDS]
- : [Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(usingFastaParser
+ ? [Keyword.EXTENDS]
+ : [Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_implements_name() async {
@@ -991,40 +962,37 @@
Future<void> test_class_noBody() async {
addTestSource('class A ^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_noBody2() async {
addTestSource('class A e^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_noBody3() async {
addTestSource('class A e^ String foo;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.EXTENDS, Keyword.IMPLEMENTS]);
}
Future<void> test_class_with() async {
addTestSource('class A extends foo with bar ^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS]);
}
Future<void> test_class_with2() async {
addTestSource('class A extends foo with bar i^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS]);
}
Future<void> test_class_with3() async {
addTestSource('class A extends foo with bar i^ { }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS]);
}
Future<void> test_class_with_name() async {
@@ -1074,22 +1042,19 @@
Future<void> test_do_break_continue_insideClass() async {
addTestSource('class A {foo() {do {^} while (true);}}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopInClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopInClass);
}
Future<void> test_do_break_continue_outsideClass() async {
addTestSource('main() {do {^} while (true);}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopOutsideClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopOutsideClass);
}
Future<void> test_empty() async {
addTestSource('^');
await computeSuggestions();
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_extension_body_beginning() async {
@@ -1133,39 +1098,37 @@
Future<void> test_extension_noBody_named() async {
addTestSource('extension E ^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.ON], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.ON]);
}
Future<void> test_extension_noBody_unnamed() async {
addTestSource('extension ^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.ON], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.ON]);
}
Future<void> test_for_break_continue_insideClass() async {
addTestSource('class A {foo() {for (int x in myList) {^}}}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopInClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopInClass);
}
Future<void> test_for_break_continue_outsideClass() async {
addTestSource('main() {for (int x in myList) {^}}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopOutsideClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopOutsideClass);
}
Future<void> test_for_expression_in() async {
addTestSource('main() {for (int x i^)}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IN], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IN]);
}
Future<void> test_for_expression_in2() async {
addTestSource('main() {for (int x in^)}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IN], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IN]);
}
Future<void> test_for_expression_in_inInitializer() async {
@@ -1189,47 +1152,39 @@
Future<void> test_for_initialization_var() async {
addTestSource('main() {for (^)}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.VAR], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.VAR]);
}
Future<void> test_function_async() async {
addTestSource('main()^');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_function_async2() async {
addTestSource('main()^{}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_function_async3() async {
addTestSource('main()a^');
await computeSuggestions();
assertSuggestKeywords(declarationKeywords,
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_function_async4() async {
addTestSource('main()a^{}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_function_async5() async {
addTestSource('main()a^ Foo foo;');
await computeSuggestions();
assertSuggestKeywords(declarationKeywords,
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_function_body_inClass_constructorInitializer() async {
@@ -1399,8 +1354,7 @@
Future<void> test_if_after_else() async {
addTestSource('main() { if (true) {} else ^ }');
await computeSuggestions();
- assertSuggestKeywords(statementStartOutsideClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartOutsideClass);
}
Future<void> test_if_afterThen_nextCloseCurlyBrace0() async {
@@ -1409,7 +1363,7 @@
var keywords = <Keyword>[];
keywords.addAll(statementStartOutsideClass);
keywords.add(Keyword.ELSE);
- assertSuggestKeywords(keywords, relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(keywords);
}
Future<void> test_if_afterThen_nextCloseCurlyBrace1() async {
@@ -1418,7 +1372,7 @@
var keywords = <Keyword>[];
keywords.addAll(statementStartOutsideClass);
keywords.add(Keyword.ELSE);
- assertSuggestKeywords(keywords, relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(keywords);
}
Future<void> test_if_afterThen_nextStatement0() async {
@@ -1427,19 +1381,19 @@
var keywords = <Keyword>[];
keywords.addAll(statementStartOutsideClass);
keywords.add(Keyword.ELSE);
- assertSuggestKeywords(keywords, relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(keywords);
}
Future<void> test_if_condition_isKeyword() async {
addTestSource('main() { if (v i^) {} }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IS]);
}
Future<void> test_if_condition_isKeyword2() async {
addTestSource('main() { if (v i^ && false) {} }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IS]);
}
Future<void> test_if_expression_in_class() async {
@@ -1637,115 +1591,104 @@
Future<void> test_import() async {
addTestSource('import "foo" deferred as foo ^;');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['show', 'hide'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['show', 'hide']);
}
Future<void> test_import_as() async {
addTestSource('import "foo" deferred ^;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.AS]);
}
Future<void> test_import_as2() async {
addTestSource('import "foo" deferred a^;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.AS]);
}
Future<void> test_import_as3() async {
addTestSource('import "foo" deferred a^');
await computeSuggestions();
- assertSuggestKeywords([Keyword.AS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.AS]);
}
Future<void> test_import_deferred() async {
addTestSource('import "foo" ^ as foo;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.DEFERRED]);
}
Future<void> test_import_deferred2() async {
addTestSource('import "foo" d^ as foo;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.DEFERRED]);
}
Future<void> test_import_deferred3() async {
addTestSource('import "foo" d^ show foo;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.AS], pseudoKeywords: ['deferred as']);
}
Future<void> test_import_deferred4() async {
addTestSource('import "foo" d^ hide foo;');
await computeSuggestions();
- assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.AS], pseudoKeywords: ['deferred as']);
}
Future<void> test_import_deferred5() async {
addTestSource('import "foo" d^');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred6() async {
addTestSource('import "foo" d^ import');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_as() async {
addTestSource('import "foo" ^;');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_as2() async {
addTestSource('import "foo" d^;');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_as3() async {
addTestSource('import "foo" ^');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_as4() async {
addTestSource('import "foo" d^');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_as5() async {
addTestSource('import "foo" sh^ import "bar"; import "baz";');
await computeSuggestions();
assertSuggestKeywords([Keyword.AS],
- pseudoKeywords: ['deferred as', 'show', 'hide'],
- relevance: DART_RELEVANCE_HIGH);
+ pseudoKeywords: ['deferred as', 'show', 'hide']);
}
Future<void> test_import_deferred_not() async {
addTestSource('import "foo" as foo ^;');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['show', 'hide'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['show', 'hide']);
}
Future<void> test_import_deferred_partial() async {
@@ -1753,7 +1696,7 @@
await computeSuggestions();
expect(replacementOffset, 30);
expect(replacementLength, 3);
- assertSuggestKeywords([Keyword.DEFERRED], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.DEFERRED]);
expect(suggestions[0].selectionOffset, 8);
expect(suggestions[0].selectionLength, 0);
}
@@ -1770,8 +1713,7 @@
expect(replacementOffset, 0);
expect(replacementLength, 3);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_import_partial2() async {
@@ -1780,8 +1722,7 @@
expect(replacementOffset, 0);
expect(replacementLength, 3);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_import_partial3() async {
@@ -1790,8 +1731,7 @@
expect(replacementOffset, 1);
expect(replacementLength, 3);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_import_partial4() async {
@@ -1800,8 +1740,7 @@
expect(replacementOffset, 0);
expect(replacementLength, 0);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_import_partial5() async {
@@ -1810,8 +1749,7 @@
expect(replacementOffset, 14);
expect(replacementLength, 3);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationKeywords);
}
Future<void> test_import_partial6() async {
@@ -1821,8 +1759,7 @@
expect(replacementOffset, 32);
expect(replacementLength, 3);
// TODO(danrubel) should not suggest declaration keywords
- assertSuggestKeywords(directiveDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationKeywords);
}
Future<void> test_integerLiteral_inArgumentList() async {
@@ -1840,20 +1777,19 @@
Future<void> test_is_expression() async {
addTestSource('main() {if (x is^)}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IS]);
}
Future<void> test_is_expression_partial() async {
addTestSource('main() {if (x i^)}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IS]);
}
Future<void> test_library() async {
addTestSource('library foo;^');
await computeSuggestions();
- assertSuggestKeywords(directiveAndDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveAndDeclarationKeywords);
}
Future<void> test_library_declaration() async {
@@ -1890,9 +1826,7 @@
Future<void> test_method_async2() async {
addTestSource('class A { foo() ^{}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_method_async3() async {
@@ -1905,9 +1839,7 @@
Future<void> test_method_async4() async {
addTestSource('class A { foo() a^{}}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async', 'async*', 'sync*'],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async', 'async*', 'sync*']);
}
Future<void> test_method_async5() async {
@@ -1927,8 +1859,7 @@
Future<void> test_method_async7() async {
addTestSource('class A { foo() ^ => Foo foo;}');
await computeSuggestions();
- assertSuggestKeywords([],
- pseudoKeywords: ['async'], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([], pseudoKeywords: ['async']);
}
Future<void> test_method_async8() async {
@@ -2109,14 +2040,13 @@
Future<void> test_mixin() async {
addTestSource('mixin M o^ { }');
await computeSuggestions();
- assertSuggestKeywords([Keyword.ON, Keyword.IMPLEMENTS],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.ON, Keyword.IMPLEMENTS]);
}
Future<void> test_mixin_afterOnClause() async {
addTestSource('mixin M on A i^ { } class A {}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.IMPLEMENTS], relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.IMPLEMENTS]);
}
Future<void> test_named_constructor_invocation() async {
@@ -2152,22 +2082,19 @@
Future<void> test_part_of() async {
addTestSource('part of foo;^');
await computeSuggestions();
- assertSuggestKeywords(directiveAndDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveAndDeclarationKeywords);
}
Future<void> test_partial_class() async {
addTestSource('cl^');
await computeSuggestions();
- assertSuggestKeywords(directiveDeclarationAndLibraryKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveDeclarationAndLibraryKeywords);
}
Future<void> test_partial_class2() async {
addTestSource('library a; cl^');
await computeSuggestions();
- assertSuggestKeywords(directiveAndDeclarationKeywords,
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords(directiveAndDeclarationKeywords);
}
Future<void> test_prefixed_field() async {
@@ -2235,29 +2162,25 @@
Future<void> test_switch_start() async {
addTestSource('main() {switch(1) {^}}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start2() async {
addTestSource('main() {switch(1) {^ case 1:}}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start3() async {
addTestSource('main() {switch(1) {^default:}}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start4() async {
addTestSource('main() {switch(1) {^ default:}}');
await computeSuggestions();
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start5() async {
@@ -2265,8 +2188,7 @@
await computeSuggestions();
expect(replacementOffset, 19);
expect(replacementLength, 1);
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start6() async {
@@ -2274,8 +2196,7 @@
await computeSuggestions();
expect(replacementOffset, 19);
expect(replacementLength, 1);
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_start7() async {
@@ -2283,8 +2204,7 @@
await computeSuggestions();
expect(replacementOffset, 20);
expect(replacementLength, 1);
- assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT],
- relevance: DART_RELEVANCE_HIGH);
+ assertSuggestKeywords([Keyword.CASE, Keyword.DEFAULT]);
}
Future<void> test_switch_statement_case_break_insideClass() async {
@@ -2320,15 +2240,13 @@
Future<void> test_while_break_continue() async {
addTestSource('main() {while (true) {^}}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopOutsideClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopOutsideClass);
}
Future<void> test_while_break_continue2() async {
addTestSource('class A {foo() {while (true) {^}}}');
await computeSuggestions();
- assertSuggestKeywords(statementStartInLoopInClass,
- relevance: DART_RELEVANCE_KEYWORD);
+ assertSuggestKeywords(statementStartInLoopInClass);
}
void _appendCompletions(
diff --git a/pkg/analysis_server/test/services/completion/dart/label_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/label_contributor_test.dart
index 7d420a4..6e8832b 100644
--- a/pkg/analysis_server/test/services/completion/dart/label_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/label_contributor_test.dart
@@ -19,9 +19,8 @@
@reflectiveTest
class LabelContributorTest extends DartCompletionContributorTest {
CompletionSuggestion assertSuggestLabel(String name,
- {int relevance = DART_RELEVANCE_DEFAULT,
- CompletionSuggestionKind kind = CompletionSuggestionKind.IDENTIFIER}) {
- var cs = assertSuggest(name, csKind: kind, relevance: relevance);
+ {CompletionSuggestionKind kind = CompletionSuggestionKind.IDENTIFIER}) {
+ var cs = assertSuggest(name, csKind: kind);
expect(cs.returnType, isNull);
var element = cs.element;
expect(element, isNotNull);
diff --git a/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
index f9de3eb..1f1a333 100644
--- a/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/library_member_contributor_test.dart
@@ -121,7 +121,7 @@
addTestSource('import "b.dart" as foo; main() {foo.^} class C { }');
await computeSuggestions();
assertSuggestClass('B');
- assertSuggestClass('B1', relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ assertSuggestClass('B1', isDeprecated: true);
assertSuggestClass('A');
assertNotSuggested('C');
}
diff --git a/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
index 7d13c2d..0cdcb90 100644
--- a/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/library_prefix_contributor_test.dart
@@ -20,9 +20,8 @@
class LibraryPrefixContributorTest extends DartCompletionContributorTest {
void assertSuggestLibraryPrefixes(List<String> expectedPrefixes) {
for (var prefix in expectedPrefixes) {
- var cs = assertSuggest(prefix,
- csKind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_DEFAULT);
+ var cs =
+ assertSuggest(prefix, csKind: CompletionSuggestionKind.IDENTIFIER);
var element = cs.element;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.LIBRARY));
diff --git a/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
index 498d1f2..e6724b6 100644
--- a/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/local_library_contributor_test.dart
@@ -133,15 +133,9 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
// A is suggested with a higher relevance
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
// D has the default relevance
assertSuggestConstructor('D', elemOffset: -1);
@@ -184,15 +178,9 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
// A is suggested with a higher relevance
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
// D has the default relevance
assertSuggestConstructor('D', elemOffset: -1);
@@ -235,12 +223,9 @@
if (suggestConstructorsWithoutNew) {
assertSuggestConstructor('A');
}
- assertSuggestFunction('af', 'int',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestTopLevelVar('m', null,
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestFunctionTypeAlias('t1', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('af', 'int');
+ assertSuggestTopLevelVar('m', null);
+ assertSuggestFunctionTypeAlias('t1', null);
assertNotSuggested('a1');
assertNotSuggested('a2');
// Suggested by LocalConstructorContributor
@@ -281,12 +266,9 @@
if (suggestConstructorsWithoutNew) {
assertSuggestConstructor('B');
}
- assertSuggestFunction('bf', 'int',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestTopLevelVar('n', null,
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestFunctionTypeAlias('t1', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bf', 'int');
+ assertSuggestTopLevelVar('n', null);
+ assertSuggestFunctionTypeAlias('t1', null);
assertNotSuggested('b1');
assertNotSuggested('b2');
// Suggested by ConstructorContributor
diff --git a/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
index 475f6e5..bb0f9a8 100644
--- a/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/local_reference_contributor_test.dart
@@ -33,7 +33,6 @@
await computeSuggestions();
assertSuggestFunction('hasLength', 'bool',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION,
defaultArgListString: 'a, b',
defaultArgumentListTextRanges: [0, 1, 3, 1]);
}
@@ -45,9 +44,7 @@
await computeSuggestions();
assertSuggestFunction('hasLength', 'bool',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION,
- defaultArgListString: null,
- defaultArgumentListTextRanges: null);
+ defaultArgListString: null, defaultArgumentListTextRanges: null);
}
Future<void> test_ArgDefaults_function_with_optional_positional() async {
@@ -60,9 +57,7 @@
await computeSuggestions();
assertSuggestFunction('foo', 'bool',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION,
- defaultArgListString: 'bar',
- defaultArgumentListTextRanges: [0, 3]);
+ defaultArgListString: 'bar', defaultArgumentListTextRanges: [0, 3]);
}
Future<void> test_ArgDefaults_function_with_required_named() async {
@@ -75,7 +70,6 @@
await computeSuggestions();
assertSuggestFunction('foo', 'bool',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION,
defaultArgListString: 'bar, baz: null',
defaultArgumentListTextRanges: [0, 3, 10, 4]);
}
@@ -115,7 +109,6 @@
await computeSuggestions();
assertSuggestMethod('foo', 'A', 'bool',
- relevance: DART_RELEVANCE_LOCAL_METHOD,
defaultArgListString: 'bar, baz: null',
defaultArgumentListTextRanges: [0, 3, 10, 4]);
}
@@ -135,8 +128,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'String');
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B');
@@ -162,8 +154,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'String');
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B');
@@ -192,8 +183,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestFunction('bar', 'String',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
@@ -223,8 +213,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestFunction('bar', 'String',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
@@ -251,8 +240,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'String');
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B');
@@ -278,8 +266,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'String');
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B');
@@ -307,11 +294,9 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestFunction('bar', 'String',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
assertSuggestFunction('boo', 'Null',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
@@ -339,14 +324,16 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance:
- DART_RELEVANCE_LOCAL_FUNCTION + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestFunction('boo', 'Null',
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance:
- DART_RELEVANCE_LOCAL_FUNCTION + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestFunction(
+ 'bar',
+ 'String',
+ kind: CompletionSuggestionKind.IDENTIFIER,
+ );
+ assertSuggestFunction(
+ 'boo',
+ 'Null',
+ kind: CompletionSuggestionKind.IDENTIFIER,
+ );
assertNotSuggested('hasLength');
assertNotSuggested('identical');
assertSuggestClass('B', kind: CompletionSuggestionKind.IDENTIFIER);
@@ -426,8 +413,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('bar', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'String');
assertNotSuggested('hasLength');
assertNotSuggested('main');
}
@@ -454,19 +440,11 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestTopLevelVar('a', 'A',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE +
- DART_RELEVANCE_BOOST_TYPE);
- assertSuggestTopLevelVar('b', 'B',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE +
- DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestTopLevelVar('c', 'C',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE +
- DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestTopLevelVar('d', 'D',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestTopLevelVar('e', 'E',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('a', 'A');
+ assertSuggestTopLevelVar('b', 'B');
+ assertSuggestTopLevelVar('c', 'C');
+ assertSuggestTopLevelVar('d', 'D');
+ assertSuggestTopLevelVar('e', 'E');
}
Future<void> test_ArgumentList_namedParam_tear_off() async {
@@ -629,9 +607,8 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestLocalVariable('a', 'int', hasTypeBoost: true);
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestLocalVariable('a', 'int');
+ assertSuggestFunction('main', null);
assertSuggestClass('A');
assertNotSuggested('Object');
}
@@ -679,8 +656,7 @@
// if newline follows first identifier
// because user is probably starting a new statement
assertSuggestLocalVariable('a', 'int');
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
assertNotSuggested('identical');
}
@@ -727,8 +703,7 @@
// if newline follows first identifier
// because user is probably starting a new statement
assertSuggestLocalVariable('a', 'int');
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
assertNotSuggested('identical');
}
@@ -742,8 +717,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestLocalVariable('a', 'A');
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
assertSuggestClass('A');
assertNotSuggested('Object');
}
@@ -760,8 +734,7 @@
await computeSuggestions();
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestMethod('y', 'A', 'Future<dynamic>',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('y', 'A', 'Future<dynamic>');
assertSuggestClass('A');
assertNotSuggested('Object');
}
@@ -804,7 +777,7 @@
// The reason is that coveringNode is VariableDeclaration, and the
// entity is BinaryExpression, so the expected type is int.
// It would be more correct to use BinaryExpression as coveringNode.
- assertSuggestLocalVariable('a', 'int', hasTypeBoost: true);
+ assertSuggestLocalVariable('a', 'int');
assertNotSuggested('Object');
assertNotSuggested('b');
}
@@ -817,7 +790,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestLocalVariable('a', 'int', hasSubtypeBoost: true);
+ assertSuggestLocalVariable('a', 'int');
assertNotSuggested('Object');
assertNotSuggested('b');
assertNotSuggested('==');
@@ -871,11 +844,9 @@
assertSuggestClass('X', elemFile: testFile);
assertSuggestClass('Z');
- assertSuggestMethod('a', 'X', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
- assertSuggestMethod('b', 'X', 'void',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
- assertSuggestFunction('localF', 'Null',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestMethod('a', 'X', null);
+ assertSuggestMethod('b', 'X', 'void');
+ assertSuggestFunction('localF', 'Null');
assertSuggestLocalVariable('f', null);
// Don't suggest locals out of scope
assertNotSuggested('r');
@@ -891,7 +862,7 @@
//assertNotSuggested('D');
//assertNotSuggested(
// 'D1', null, true, COMPLETION_RELEVANCE_LOW);
- assertSuggestFunction('D2', 'Z', relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('D2', 'Z');
assertNotSuggested('EE');
// hidden element suggested as low relevance
//assertNotSuggested('F');
@@ -904,16 +875,13 @@
assertNotSuggested('_T2');
//assertNotSuggested('T3');
assertNotSuggested('_T4');
- assertSuggestTopLevelVar('T5', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestTopLevelVar('_T6', null, relevance: DART_RELEVANCE_DEFAULT);
+ assertSuggestTopLevelVar('T5', 'int');
+ assertSuggestTopLevelVar('_T6', null);
assertNotSuggested('==');
- assertSuggestGetter('T7', 'String',
- relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
- assertSuggestSetter('T8', relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
- assertSuggestGetter('clog', 'int',
- relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
- assertSuggestSetter('blog', relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
+ assertSuggestGetter('T7', 'String');
+ assertSuggestSetter('T8');
+ assertSuggestGetter('clog', 'int');
+ assertSuggestSetter('blog');
// TODO (danrubel) suggest HtmlElement as low relevance
assertNotSuggested('HtmlElement');
assertNotSuggested('Uri');
@@ -1269,9 +1237,8 @@
assertSuggestClass('X');
assertSuggestClass('Z');
- assertSuggestMethod('a', 'X', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
- assertSuggestMethod('b', 'X', 'void',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('a', 'X', null);
+ assertSuggestMethod('b', 'X', 'void');
assertSuggestLocalVariable('f', null);
// Don't suggest locals out of scope
assertNotSuggested('r');
@@ -1284,7 +1251,7 @@
// hidden element suggested as low relevance
assertNotSuggested('D');
assertNotSuggested('D1');
- assertSuggestFunction('D2', 'Z', relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('D2', 'Z');
// unimported elements suggested with low relevance
assertNotSuggested('D3');
//assertNotSuggested('EE');
@@ -1527,7 +1494,7 @@
''');
await computeSuggestions();
- assertSuggestSetter('foo', relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
+ assertSuggestSetter('foo');
}
Future<void> test_Block_unimported() async {
@@ -1678,7 +1645,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestParameter('e', 'E');
- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('a', 'A', null);
assertNotSuggested('Object');
assertNotSuggested('x');
}
@@ -1692,7 +1659,7 @@
expect(replacementLength, 0);
assertSuggestParameter('e', null);
assertSuggestParameter('s', 'StackTrace');
- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('a', 'A', null);
assertNotSuggested('Object');
assertNotSuggested('x');
}
@@ -1710,8 +1677,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- var suggestionA = assertSuggestClass('A',
- relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ var suggestionA = assertSuggestClass('A', isDeprecated: true);
if (suggestionA != null) {
expect(suggestionA.element.isDeprecated, isTrue);
expect(suggestionA.element.isPrivate, isFalse);
@@ -1924,8 +1890,7 @@
await computeSuggestions();
// top level results are partially filtered based on first char
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
// TODO (danrubel) getter is being suggested instead of top level var
//assertNotSuggested('T1');
}
@@ -1946,12 +1911,10 @@
assertNotSuggested('x');
assertSuggestLocalVariable('f', null);
- assertSuggestMethod('foo', 'C', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('foo', 'C', null);
assertSuggestClass('C');
- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestFunction('F2', null);
+ assertSuggestTopLevelVar('T2', 'int');
assertNotSuggested('A');
assertNotSuggested('F1');
// TODO (danrubel) getter is being suggested instead of top level var
@@ -1973,8 +1936,7 @@
await computeSuggestions();
// top level results are partially filtered based on first char
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
// TODO (danrubel) getter is being suggested instead of top level var
//assertNotSuggested('T1');
}
@@ -1995,12 +1957,10 @@
assertNotSuggested('x');
assertSuggestLocalVariable('f', null);
- assertSuggestMethod('foo', 'C', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('foo', 'C', null);
assertSuggestClass('C');
- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestFunction('F2', null);
+ assertSuggestTopLevelVar('T2', 'int');
assertNotSuggested('A');
assertNotSuggested('F1');
// TODO (danrubel) getter is being suggested instead of top level var
@@ -2022,8 +1982,7 @@
await computeSuggestions();
// top level results are partially filtered based on first char
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
// TODO (danrubel) getter is being suggested instead of top level var
//assertNotSuggested('T1');
}
@@ -2075,7 +2034,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('foo', 'int', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('foo', 'int');
}
Future<void> test_ConstructorFieldInitializer_value() async {
@@ -2091,11 +2050,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestTopLevelVar(
- 'foo',
- 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE,
- );
+ assertSuggestTopLevelVar('foo', 'int');
}
Future<void> test_ConstructorName_importedClass() async {
@@ -2218,9 +2173,8 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('foo', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestMethod('a', 'A', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestFunction('foo', null);
+ assertSuggestMethod('a', 'A', null);
assertSuggestClass('A');
assertNotSuggested('String');
assertNotSuggested('identical');
@@ -2254,18 +2208,15 @@
}''');
await computeSuggestions();
{
- var suggestion = assertSuggestField('myField', 'int',
- relevance: DART_RELEVANCE_LOCAL_FIELD);
+ var suggestion = assertSuggestField('myField', 'int');
assertDoc(suggestion);
}
{
- var suggestion = assertSuggestMethod('myMethod', 'C', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ var suggestion = assertSuggestMethod('myMethod', 'C', null);
assertDoc(suggestion);
}
{
- var suggestion = assertSuggestGetter('myGetter', 'int',
- relevance: DART_RELEVANCE_LOCAL_ACCESSOR);
+ var suggestion = assertSuggestGetter('myGetter', 'int');
assertDoc(suggestion);
}
}
@@ -2339,13 +2290,11 @@
assertDoc(suggestion);
}
{
- var suggestion = assertSuggestFunction('myFunction', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('myFunction', 'void');
assertDoc(suggestion);
}
{
- var suggestion = assertSuggestTopLevelVar('myVariable', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ var suggestion = assertSuggestTopLevelVar('myVariable', 'int');
assertDoc(suggestion);
}
}
@@ -2384,8 +2333,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2405,8 +2354,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2425,8 +2374,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2447,8 +2396,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2467,8 +2416,8 @@
await computeSuggestions();
assertSuggestEnum('E');
- assertSuggestEnumConst('E.one', hasTypeBoost: true);
- assertSuggestEnumConst('E.two', hasTypeBoost: true);
+ assertSuggestEnumConst('E.one');
+ assertSuggestEnumConst('E.two');
assertSuggestEnum('F');
assertSuggestEnumConst('F.three');
@@ -2627,10 +2576,8 @@
assertNotSuggested('A');
assertNotSuggested('F1');
assertSuggestClass('C');
- assertSuggestMethod('foo', 'C', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
- assertSuggestMethod('bar', 'C', 'void',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('foo', 'C', null);
+ assertSuggestMethod('bar', 'C', 'void');
assertSuggestFunctionTypeAlias('F2', 'int');
assertSuggestClass('Clz');
assertSuggestClass('C');
@@ -2888,8 +2835,7 @@
await computeSuggestions();
// We don't actually use anything from the `for`, and `v` is suggested
// just because it is a visible top-level declaration.
- assertSuggestTopLevelVar('v', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('v', 'int');
}
Future<void> test_ForEachStatement() async {
@@ -3092,8 +3038,7 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
assertSuggestLocalVariable('index', 'int');
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
assertNotSuggested('bar');
}
@@ -3105,8 +3050,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, hasLength(2));
expect(suggestion.parameterNames[0], 'x');
expect(suggestion.parameterTypes[0], 'dynamic');
@@ -3124,8 +3068,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, hasLength(2));
expect(suggestion.parameterNames[0], 'x');
expect(suggestion.parameterTypes[0], 'dynamic');
@@ -3143,8 +3086,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, hasLength(2));
expect(suggestion.parameterNames[0], 'x');
expect(suggestion.parameterTypes[0], 'dynamic');
@@ -3162,8 +3104,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, isEmpty);
expect(suggestion.parameterTypes, isEmpty);
expect(suggestion.requiredParameterCount, 0);
@@ -3178,8 +3119,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, hasLength(2));
expect(suggestion.parameterNames[0], 'x');
expect(suggestion.parameterTypes[0], 'dynamic');
@@ -3197,8 +3137,7 @@
}
''');
await computeSuggestions();
- var suggestion = assertSuggestFunction('m', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var suggestion = assertSuggestFunction('m', 'void');
expect(suggestion.parameterNames, hasLength(2));
expect(suggestion.parameterNames[0], 'x');
expect(suggestion.parameterTypes[0], 'dynamic');
@@ -3326,13 +3265,11 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- var f = assertSuggestFunction('foo', 'String',
- isDeprecated: false, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ var f = assertSuggestFunction('foo', 'String', isDeprecated: false);
if (f != null) {
expect(f.element.isPrivate, isFalse);
}
- assertSuggestFunction('bar', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('bar', 'void');
assertSuggestParameter('args', 'List<dynamic>');
assertSuggestParameter('b', 'R');
assertNotSuggested('Object');
@@ -3387,8 +3324,8 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_DEFAULT);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('Object');
assertSuggestClass('A');
assertNotSuggested('==');
@@ -3404,8 +3341,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestLocalVariable('a', null);
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
assertSuggestClass('A');
assertNotSuggested('Object');
}
@@ -3427,8 +3363,8 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_DEFAULT);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('Object');
assertSuggestClass('A');
assertNotSuggested('==');
@@ -3451,8 +3387,8 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
- assertSuggestField('b', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestField('_c', 'X', relevance: DART_RELEVANCE_DEFAULT);
+ assertSuggestField('b', null);
+ assertSuggestField('_c', 'X');
assertNotSuggested('Object');
assertSuggestClass('A');
assertNotSuggested('==');
@@ -3506,8 +3442,7 @@
main(aaa, bbb) {}''');
await computeSuggestions();
assertSuggestFunction('main', null,
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
}
Future<void> test_inDartDoc_reference4() async {
@@ -3516,8 +3451,7 @@
main(aaa, bbb) {}''');
await computeSuggestions();
assertSuggestFunction('main', null,
- kind: CompletionSuggestionKind.IDENTIFIER,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ kind: CompletionSuggestionKind.IDENTIFIER);
}
Future<void> test_IndexExpression() async {
@@ -3536,12 +3470,10 @@
assertNotSuggested('x');
assertSuggestLocalVariable('f', null);
- assertSuggestMethod('foo', 'C', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('foo', 'C', null);
assertSuggestClass('C');
- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestFunction('F2', null);
+ assertSuggestTopLevelVar('T2', 'int');
assertNotSuggested('A');
assertNotSuggested('F1');
// TODO (danrubel) getter is being suggested instead of top level var
@@ -3563,8 +3495,7 @@
await computeSuggestions();
// top level results are partially filtered based on first char
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
// TODO (danrubel) getter is being suggested instead of top level var
//assertNotSuggested('T1');
}
@@ -3700,15 +3631,9 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
assertSuggestConstructor('D', elemOffset: -1);
}
@@ -3722,15 +3647,9 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
assertSuggestConstructor('D', elemOffset: -1);
}
@@ -3774,12 +3693,8 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
assertSuggestConstructor('C', elemOffset: -1);
}
@@ -3793,12 +3708,8 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
assertSuggestConstructor('C', elemOffset: -1);
}
@@ -3823,15 +3734,9 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
assertSuggestConstructor('D', elemOffset: -1);
}
@@ -3844,15 +3749,9 @@
}''');
await computeSuggestions();
- assertSuggestConstructor('A',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_TYPE);
- assertSuggestConstructor('B',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
- assertSuggestConstructor('C',
- elemOffset: -1,
- relevance: DART_RELEVANCE_DEFAULT + DART_RELEVANCE_BOOST_SUBTYPE);
+ assertSuggestConstructor('A', elemOffset: -1);
+ assertSuggestConstructor('B', elemOffset: -1);
+ assertSuggestConstructor('C', elemOffset: -1);
assertSuggestConstructor('D', elemOffset: -1);
}
@@ -3879,9 +3778,8 @@
assertNotSuggested('F1');
assertNotSuggested('D1');
assertNotSuggested('C1');
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestTopLevelVar('T2', 'int');
+ assertSuggestFunction('F2', null);
assertSuggestFunctionTypeAlias('D2', 'dynamic');
assertSuggestClass('C2');
assertSuggestLocalVariable('name', 'String');
@@ -3962,10 +3860,8 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
assertSuggestLocalVariable('a', null);
- assertSuggestFunction('main', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestFunction('foo', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('main', null);
+ assertSuggestFunction('foo', null);
assertNotSuggested('bar');
assertSuggestClass('A');
assertNotSuggested('Object');
@@ -4068,10 +3964,8 @@
assertNotSuggested('T1');
assertNotSuggested('newT1');
assertNotSuggested('z');
- assertSuggestTopLevelVar('m', 'dynamic',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestFunction('newer', 'String',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestTopLevelVar('m', 'dynamic');
+ assertSuggestFunction('newer', 'String');
}
Future<void> test_Literal_list() async {
@@ -4222,9 +4116,8 @@
assertNotSuggested('F1');
assertNotSuggested('D1');
assertNotSuggested('C1');
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
- assertSuggestFunction('F2', null, relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestTopLevelVar('T2', 'int');
+ assertSuggestFunction('F2', null);
assertSuggestFunctionTypeAlias('D2', 'dynamic');
assertSuggestClass('C2');
}
@@ -4248,8 +4141,7 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
assertNotSuggested('T1');
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
}
Future<void> test_MapLiteralEntry2() async {
@@ -4271,8 +4163,7 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
assertNotSuggested('T1');
- assertSuggestTopLevelVar('T2', 'int',
- relevance: DART_RELEVANCE_LOCAL_TOP_LEVEL_VARIABLE);
+ assertSuggestTopLevelVar('T2', 'int');
}
Future<void> test_method_inClass() async {
@@ -4559,20 +4450,17 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- var methodA = assertSuggestMethod('a', 'A', 'Z',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ var methodA = assertSuggestMethod('a', 'A', 'Z');
if (methodA != null) {
expect(methodA.element.isDeprecated, isFalse);
expect(methodA.element.isPrivate, isFalse);
}
- var getterF = assertSuggestGetter('f', 'X',
- relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ var getterF = assertSuggestGetter('f', 'X', isDeprecated: true);
if (getterF != null) {
expect(getterF.element.isDeprecated, isTrue);
expect(getterF.element.isPrivate, isFalse);
}
- var getterG =
- assertSuggestGetter('_g', null, relevance: DART_RELEVANCE_DEFAULT);
+ var getterG = assertSuggestGetter('_g', null);
if (getterG != null) {
expect(getterG.element.isDeprecated, isFalse);
expect(getterG.element.isPrivate, isTrue);
@@ -4604,9 +4492,8 @@
assertNotSuggested('a1');
assertNotSuggested('a2');
- assertSuggestMethod('a3', 'A', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
- assertSuggestField('a4', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestMethod('a3', 'A', null);
+ assertSuggestField('a4', null);
assertNotSuggested('b1');
assertNotSuggested('b2');
assertNotSuggested('b3');
@@ -4632,22 +4519,19 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- var methodA =
- assertSuggestMethod('_a', 'A', 'Z', relevance: DART_RELEVANCE_DEFAULT);
+ var methodA = assertSuggestMethod('_a', 'A', 'Z');
if (methodA != null) {
expect(methodA.element.isDeprecated, isFalse);
expect(methodA.element.isPrivate, isTrue);
}
- var getterF = assertSuggestField('f', 'X',
- relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ var getterF = assertSuggestField('f', 'X', isDeprecated: true);
if (getterF != null) {
expect(getterF.element.isDeprecated, isTrue);
expect(getterF.element.isPrivate, isFalse);
expect(getterF.element.parameters, isNull);
}
// If user did not type '_' then relevance of private members is not raised
- var getterG =
- assertSuggestField('_g', null, relevance: DART_RELEVANCE_DEFAULT);
+ var getterG = assertSuggestField('_g', null);
if (getterG != null) {
expect(getterG.element.isDeprecated, isFalse);
expect(getterG.element.isPrivate, isTrue);
@@ -4672,14 +4556,12 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
- var methodA =
- assertSuggestMethod('_a', 'A', 'Z', relevance: DART_RELEVANCE_DEFAULT);
+ var methodA = assertSuggestMethod('_a', 'A', 'Z');
if (methodA != null) {
expect(methodA.element.isDeprecated, isFalse);
expect(methodA.element.isPrivate, isTrue);
}
- var getterF = assertSuggestField('f', 'X',
- relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ var getterF = assertSuggestField('f', 'X', isDeprecated: true);
if (getterF != null) {
expect(getterF.element.isDeprecated, isTrue);
expect(getterF.element.isPrivate, isFalse);
@@ -4687,8 +4569,7 @@
}
// If user prefixed completion with '_' then suggestion of private members
// should be the same as public members
- var getterG =
- assertSuggestField('_g', null, relevance: DART_RELEVANCE_DEFAULT);
+ var getterG = assertSuggestField('_g', null);
if (getterG != null) {
expect(getterG.element.isDeprecated, isFalse);
expect(getterG.element.isPrivate, isTrue);
@@ -4711,8 +4592,7 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- var methodA = assertSuggestMethod('a', 'A', 'Z',
- relevance: DART_RELEVANCE_LOW, isDeprecated: true);
+ var methodA = assertSuggestMethod('a', 'A', 'Z', isDeprecated: true);
if (methodA != null) {
expect(methodA.element.isDeprecated, isTrue);
expect(methodA.element.isPrivate, isFalse);
@@ -4739,11 +4619,9 @@
expect(replacementOffset, completionOffset);
expect(replacementLength, 0);
- assertSuggestFunction('foo', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestFunction('bar', 'void',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
- assertSuggestMethod('a', 'A', 'Z', relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestFunction('foo', null);
+ assertSuggestFunction('bar', 'void');
+ assertSuggestMethod('a', 'A', 'Z');
assertSuggestParameter('x', 'X');
assertSuggestParameter('y', 'int');
assertNotSuggested('String');
@@ -5160,7 +5038,7 @@
class B extends A {m() {^}}
''');
await computeSuggestions();
- assertSuggestMethod('m', 'B', null, relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('m', 'B', null);
}
Future<void> test_parameterName_excludeTypes() async {
@@ -5424,8 +5302,7 @@
expect(replacementLength, 1);
assertNotSuggested('A');
assertSuggestClass('X');
- assertSuggestMethod('foo', 'X', null,
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('foo', 'X', null);
assertNotSuggested('bar');
assertNotSuggested('_B');
}
@@ -5610,7 +5487,7 @@
Future<void> test_shadowed_name() async {
addTestSource('var a; class A { var a; m() { ^ } }');
await computeSuggestions();
- assertSuggestField('a', null, relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestField('a', null);
}
Future<void> test_static_field() async {
@@ -5711,8 +5588,7 @@
await computeSuggestions();
assertSuggestClass('A');
- assertSuggestMethod('g', 'A', 'String',
- relevance: DART_RELEVANCE_LOCAL_METHOD);
+ assertSuggestMethod('g', 'A', 'String');
assertSuggestLocalVariable('t', null);
assertNotSuggested('String');
}
@@ -5722,10 +5598,9 @@
addTestSource('g(int x) {var t; switch(x) {case 0: var bar; b^}}');
await computeSuggestions();
- assertSuggestFunction('g', 'dynamic',
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('g', 'dynamic');
assertSuggestLocalVariable('t', 'dynamic');
- assertSuggestParameter('x', 'int', relevance: DART_RELEVANCE_PARAMETER);
+ assertSuggestParameter('x', 'int');
assertSuggestLocalVariable('bar', 'dynamic');
assertNotSuggested('String');
}
@@ -6138,8 +6013,7 @@
assertNotSuggested('X');
assertNotSuggested('foo1');
assertNotSuggested('bar1');
- assertSuggestFunction('foo2', null,
- relevance: DART_RELEVANCE_LOCAL_FUNCTION);
+ assertSuggestFunction('foo2', null);
assertNotSuggested('bar2');
assertNotSuggested('_B');
assertSuggestClass('Y');
diff --git a/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
index b014fe0..68a9878 100644
--- a/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/named_constructor_contributor_test.dart
@@ -20,9 +20,8 @@
class NamedConstructorContributorTest extends DartCompletionContributorTest {
CompletionSuggestion assertSuggestNamedConstructor(
String name, String returnType,
- [int relevance = DART_RELEVANCE_DEFAULT,
- CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION]) {
- var cs = assertSuggest(name, csKind: kind, relevance: relevance);
+ [CompletionSuggestionKind kind = CompletionSuggestionKind.INVOCATION]) {
+ var cs = assertSuggest(name, csKind: kind);
var element = cs.element;
expect(element, isNotNull);
expect(element.kind, equals(ElementKind.CONSTRUCTOR));
diff --git a/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
index d0df1f8..7edebfc 100644
--- a/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/override_contributor_test.dart
@@ -525,7 +525,6 @@
failedCompletion('expected $completion', suggestions);
}
expect(cs.kind, equals(CompletionSuggestionKind.OVERRIDE));
- expect(cs.relevance, equals(DART_RELEVANCE_HIGH));
if (selectionOffset != null && selectionLength != null) {
expect(cs.selectionOffset, selectionOffset);
expect(cs.selectionLength, selectionLength);
diff --git a/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
index 0ee70bf..8698dd5 100644
--- a/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/static_member_contributor_test.dart
@@ -50,8 +50,8 @@
addTestSource('enum E { one, two } main() {E.^}');
await computeSuggestions();
assertNotSuggested('E');
- assertSuggestEnumConst('one', relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestEnumConst('two', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestEnumConst('one');
+ assertSuggestEnumConst('two');
assertNotSuggested('index');
assertSuggestField('values', 'List<E>');
}
@@ -60,8 +60,8 @@
addTestSource('enum E { one, two } main() {E.o^}');
await computeSuggestions();
assertNotSuggested('E');
- assertSuggestEnumConst('one', relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestEnumConst('two', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestEnumConst('one');
+ assertSuggestEnumConst('two');
assertNotSuggested('index');
assertSuggestField('values', 'List<E>');
}
@@ -70,8 +70,8 @@
addTestSource('enum E { one, two } main() {E.^ int g;}');
await computeSuggestions();
assertNotSuggested('E');
- assertSuggestEnumConst('one', relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestEnumConst('two', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestEnumConst('one');
+ assertSuggestEnumConst('two');
assertNotSuggested('index');
assertSuggestField('values', 'List<E>');
}
@@ -86,8 +86,8 @@
addTestSource('enum E { one, two } main() {E.^.}');
await computeSuggestions();
assertNotSuggested('E');
- assertSuggestEnumConst('one', relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestEnumConst('two', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestEnumConst('one');
+ assertSuggestEnumConst('two');
assertNotSuggested('index');
assertSuggestField('values', 'List<E>');
}
@@ -102,8 +102,8 @@
addTestSource('enum E { one, two } main() {E.^.o}');
await computeSuggestions();
assertNotSuggested('E');
- assertSuggestEnumConst('one', relevance: DART_RELEVANCE_LOCAL_FIELD);
- assertSuggestEnumConst('two', relevance: DART_RELEVANCE_LOCAL_FIELD);
+ assertSuggestEnumConst('one');
+ assertSuggestEnumConst('two');
assertNotSuggested('index');
assertSuggestField('values', 'List<E>');
}
diff --git a/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
index 3ac6f0f..2d7372c 100644
--- a/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/type_member_contributor_test.dart
@@ -3053,10 +3053,8 @@
expect(replacementLength, 0);
assertSuggestGetter('f', 'X');
assertSuggestGetter('_g', null);
- assertSuggestField(r'$p', 'dynamic',
- relevance: useNewRelevance ? null : DART_RELEVANCE_LOW);
- assertSuggestMethod(r'$q', 'I', 'void',
- relevance: useNewRelevance ? null : DART_RELEVANCE_LOW);
+ assertSuggestField(r'$p', 'dynamic');
+ assertSuggestMethod(r'$q', 'I', 'void');
assertNotSuggested('b');
assertNotSuggested('_c');
assertNotSuggested('d');
@@ -3829,8 +3827,7 @@
assertNotSuggested('fs2');
assertSuggestMethod('mi2', 'C2', null);
assertNotSuggested('ms2');
- assertSuggestMethod('m', 'C2', null,
- relevance: useNewRelevance ? null : DART_RELEVANCE_HIGH);
+ assertSuggestMethod('m', 'C2', null);
assertNotSuggested('fi3');
assertNotSuggested('fs3');
assertNotSuggested('mi3');
diff --git a/pkg/analysis_server/test/services/completion/dart/uri_contributor_test.dart b/pkg/analysis_server/test/services/completion/dart/uri_contributor_test.dart
index bcfffa1..cf86d79 100644
--- a/pkg/analysis_server/test/services/completion/dart/uri_contributor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/uri_contributor_test.dart
@@ -123,8 +123,7 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
- assertSuggest('dart:core',
- csKind: CompletionSuggestionKind.IMPORT, relevance: DART_RELEVANCE_LOW);
+ assertSuggest('dart:core', csKind: CompletionSuggestionKind.IMPORT);
assertNotSuggested('dart:_internal');
assertSuggest('dart:async', csKind: CompletionSuggestionKind.IMPORT);
assertSuggest('dart:math', csKind: CompletionSuggestionKind.IMPORT);
@@ -136,8 +135,7 @@
expect(replacementOffset, completionOffset - 1);
expect(replacementLength, 1);
assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
- assertSuggest('dart:core',
- csKind: CompletionSuggestionKind.IMPORT, relevance: DART_RELEVANCE_LOW);
+ assertSuggest('dart:core', csKind: CompletionSuggestionKind.IMPORT);
assertNotSuggested('dart:_internal');
assertSuggest('dart:async', csKind: CompletionSuggestionKind.IMPORT);
assertSuggest('dart:math', csKind: CompletionSuggestionKind.IMPORT);
diff --git a/pkg/analysis_server/test/src/cider/completion_test.dart b/pkg/analysis_server/test/src/cider/completion_test.dart
index e8abf70..cef8019 100644
--- a/pkg/analysis_server/test/src/cider/completion_test.dart
+++ b/pkg/analysis_server/test/src/cider/completion_test.dart
@@ -416,6 +416,21 @@
_assertHasClass(text: 'A');
}
+ Future<void> test_limitedResolution_inPart() async {
+ newFile('/workspace/dart/test/lib/a.dart', content: r'''
+part 'test.dart';
+class A {}
+''');
+
+ await _compute(r'''
+part of 'a.dart';
+^
+''');
+
+ _assertHasClass(text: 'int');
+ _assertHasClass(text: 'A');
+ }
+
Future<void> test_limitedResolution_unit_function_body() async {
_configureToCheckNotResolved(
identifiers: {'print'},
diff --git a/pkg/analysis_server/test/src/services/correction/assist/flutter_wrap_sized_box.dart b/pkg/analysis_server/test/src/services/correction/assist/flutter_wrap_sized_box.dart
new file mode 100644
index 0000000..b9b6947
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/assist/flutter_wrap_sized_box.dart
@@ -0,0 +1,122 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/correction/assist.dart';
+import 'package:analyzer_plugin/utilities/assist/assist.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'assist_processor.dart';
+
+// todo: update for SizedBox
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(FlutterWrapSizedBoxTest);
+ });
+}
+
+@reflectiveTest
+class FlutterWrapSizedBoxTest extends AssistProcessorTest {
+ @override
+ AssistKind get kind => DartAssistKind.FLUTTER_WRAP_SIZED_BOX;
+
+ Future<void> test_aroundContainer() async {
+ addFlutterPackage();
+ await resolveTestUnit('''
+import 'package:flutter/widgets.dart';
+class FakeFlutter {
+ main() {
+ return /*caret*/Container();
+ }
+}
+''');
+ await assertHasAssist('''
+import 'package:flutter/widgets.dart';
+class FakeFlutter {
+ main() {
+ return SizedBox(child: Container());
+ }
+}
+''');
+ }
+
+ Future<void> test_aroundNamedConstructor() async {
+ addFlutterPackage();
+ await resolveTestUnit('''
+import 'package:flutter/widgets.dart';
+
+class MyWidget extends StatelessWidget {
+ MyWidget.named();
+
+ Widget build(BuildContext context) => null;
+}
+
+main() {
+ return MyWidget./*caret*/named();
+}
+''');
+ await assertHasAssist('''
+import 'package:flutter/widgets.dart';
+
+class MyWidget extends StatelessWidget {
+ MyWidget.named();
+
+ Widget build(BuildContext context) => null;
+}
+
+main() {
+ return SizedBox(child: MyWidget.named());
+}
+''');
+ }
+
+ Future<void> test_aroundSizedBox() async {
+ addFlutterPackage();
+ await resolveTestUnit('''
+import 'package:flutter/widgets.dart';
+class FakeFlutter {
+ main() {
+ return /*caret*/SizedBox();
+ }
+}
+''');
+ await assertNoAssist();
+ }
+
+ Future<void> test_assignment() async {
+ addFlutterPackage();
+ await resolveTestUnit('''
+import 'package:flutter/widgets.dart';
+
+main() {
+ Widget w;
+ w = /*caret*/Container();
+}
+''');
+ await assertHasAssist('''
+import 'package:flutter/widgets.dart';
+
+main() {
+ Widget w;
+ w = SizedBox(child: Container());
+}
+''');
+ }
+
+ Future<void> test_expressionFunctionBody() async {
+ addFlutterPackage();
+ await resolveTestUnit('''
+import 'package:flutter/widgets.dart';
+class FakeFlutter {
+ main() => /*caret*/Container();
+}
+''');
+ await assertHasAssist('''
+import 'package:flutter/widgets.dart';
+class FakeFlutter {
+ main() => SizedBox(child: Container());
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/assist/test_all.dart b/pkg/analysis_server/test/src/services/correction/assist/test_all.dart
index 18c3539..a521dec 100644
--- a/pkg/analysis_server/test/src/services/correction/assist/test_all.dart
+++ b/pkg/analysis_server/test/src/services/correction/assist/test_all.dart
@@ -58,6 +58,7 @@
import 'flutter_wrap_generic_test.dart' as flutter_wrap_generic;
import 'flutter_wrap_padding_test.dart' as flutter_wrap_padding;
import 'flutter_wrap_row_test.dart' as flutter_wrap_row;
+import 'flutter_wrap_sized_box.dart' as flutter_wrap_sized_box;
import 'flutter_wrap_stream_builder_test.dart' as flutter_wrap_stream_builder;
import 'import_add_show_test.dart' as import_add_show;
import 'inline_invocation_test.dart' as inline_invocation;
@@ -135,6 +136,7 @@
flutter_wrap_generic.main();
flutter_wrap_padding.main();
flutter_wrap_row.main();
+ flutter_wrap_sized_box.main();
flutter_wrap_stream_builder.main();
import_add_show.main();
inline_invocation.main();
diff --git a/pkg/analysis_server/test/src/services/correction/fix/add_missing_enum_case_clauses_test.dart b/pkg/analysis_server/test/src/services/correction/fix/add_missing_enum_case_clauses_test.dart
index 41407c0..09f61ed 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/add_missing_enum_case_clauses_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/add_missing_enum_case_clauses_test.dart
@@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:analysis_server/src/services/correction/fix.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -20,17 +21,21 @@
@override
FixKind get kind => DartFixKind.ADD_MISSING_ENUM_CASE_CLAUSES;
- Future<void> assertHasFixWithFilter(String expected) async {
- var noError = true;
- await assertHasFix(expected, errorFilter: (error) {
- if (noError &&
+ bool Function(AnalysisError) get _filter {
+ var hasError = false;
+ return (error) {
+ if (!hasError &&
error.errorCode ==
StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH) {
- noError = false;
+ hasError = true;
return true;
}
return false;
- });
+ };
+ }
+
+ Future<void> assertHasFixWithFilter(String expected) async {
+ await assertHasFix(expected, errorFilter: _filter);
}
Future<void> test_empty() async {
@@ -59,6 +64,17 @@
''');
}
+ Future<void> test_incomplete_switchStatement() async {
+ await resolveTestUnit(r'''
+enum E {a, b, c}
+
+void f(E e) {
+ switch(e
+}
+''');
+ await assertNoFix(errorFilter: _filter);
+ }
+
Future<void> test_nonEmpty() async {
await resolveTestUnit('''
enum E {a, b, c}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_method_declaration_test.dart b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_method_declaration_test.dart
new file mode 100644
index 0000000..6389eaf
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_method_declaration_test.dart
@@ -0,0 +1,45 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/linter/lint_names.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'bulk_fix_processor.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(RemoveMethodDeclarationTest);
+ });
+}
+
+@reflectiveTest
+class RemoveMethodDeclarationTest extends BulkFixProcessorTest {
+ @override
+ String get lintCode => LintNames.unnecessary_overrides;
+
+ Future<void> test_singleFile() async {
+ await resolveTestUnit('''
+class A {
+ int foo;
+ int bar() => 0;
+}
+
+class B extends A {
+ @override
+ int get foo => super.foo;
+ @override
+ int bar() => super.bar();
+}
+''');
+ await assertHasFix('''
+class A {
+ int foo;
+ int bar() => 0;
+}
+
+class B extends A {
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_this_expression_test.dart b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_this_expression_test.dart
new file mode 100644
index 0000000..06f6938
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_this_expression_test.dart
@@ -0,0 +1,41 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/linter/lint_names.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'bulk_fix_processor.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(RemoveThisExpressionTest);
+ });
+}
+
+@reflectiveTest
+class RemoveThisExpressionTest extends BulkFixProcessorTest {
+ @override
+ String get lintCode => LintNames.unnecessary_this;
+
+ Future<void> test_singleFile() async {
+ await resolveTestUnit('''
+class A {
+ int x;
+ A(int x) : this.x = x;
+ void foo() {
+ this.foo();
+ }
+}
+''');
+ await assertHasFix('''
+class A {
+ int x;
+ A(int x) : x = x;
+ void foo() {
+ foo();
+ }
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_type_annotation_test.dart b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_type_annotation_test.dart
index 55d013f..f164e06 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_type_annotation_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/bulk/remove_type_annotation_test.dart
@@ -12,6 +12,7 @@
defineReflectiveTests(RemoveDynamicTypeAnnotationTest);
defineReflectiveTests(RemoveSetterReturnTypeAnnotationTest);
defineReflectiveTests(RemoveTypeAnnotationOnClosureParamsTest);
+ defineReflectiveTests(TypeInitFormalsTest);
});
}
@@ -75,3 +76,34 @@
''');
}
}
+
+@reflectiveTest
+class TypeInitFormalsTest extends BulkFixProcessorTest {
+ @override
+ String get lintCode => LintNames.type_init_formals;
+
+ Future<void> test_singleFile() async {
+ await resolveTestUnit('''
+class C {
+ int f;
+ C(int this.f);
+}
+
+class Point {
+ int x, y;
+ Point(int this.x, int this.y);
+}
+''');
+ await assertHasFix('''
+class C {
+ int f;
+ C(this.f);
+}
+
+class Point {
+ int x, y;
+ Point(this.x, this.y);
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/bulk/replace_with_tear_off_test.dart b/pkg/analysis_server/test/src/services/correction/fix/bulk/replace_with_tear_off_test.dart
new file mode 100644
index 0000000..5be6f3f
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/bulk/replace_with_tear_off_test.dart
@@ -0,0 +1,43 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/linter/lint_names.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'bulk_fix_processor.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(ReplaceWithTearOffTest);
+ });
+}
+
+@reflectiveTest
+class ReplaceWithTearOffTest extends BulkFixProcessorTest {
+ @override
+ String get lintCode => LintNames.unnecessary_lambdas;
+
+ Future<void> test_singleFile() async {
+ await resolveTestUnit('''
+Function f() => (name) {
+ print(name);
+};
+
+void foo(){}
+Function f2() {
+ return () {
+ foo();
+ };
+}
+''');
+ await assertHasFix('''
+Function f() => print;
+
+void foo(){}
+Function f2() {
+ return foo;
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/bulk/test_all.dart b/pkg/analysis_server/test/src/services/correction/fix/bulk/test_all.dart
index edac3a0..25bddfa 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/bulk/test_all.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/bulk/test_all.dart
@@ -22,7 +22,9 @@
import 'remove_empty_else_test.dart' as remove_empty_else;
import 'remove_empty_statement_test.dart' as remove_empty_statement;
import 'remove_initializer_test.dart' as remove_initializer;
+import 'remove_method_declaration_test.dart' as remove_method_declaration;
import 'remove_operator_test.dart' as remove_operator;
+import 'remove_this_expression_test.dart' as remove_this_expression;
import 'remove_type_annotation_test.dart' as remove_type_annotation;
import 'remove_unnecessary_const_test.dart' as remove_unnecessary_const;
import 'remove_unnecessary_new_test.dart' as remove_unnecessary_new;
@@ -31,6 +33,7 @@
import 'replace_with_conditional_assignment_test.dart'
as replace_with_conditional_assignment;
import 'replace_with_is_empty_test.dart' as replace_with_is_empty;
+import 'replace_with_tear_off_test.dart' as replace_with_tear_off;
import 'replace_with_var_test.dart' as replace_with_var;
import 'use_curly_braces_test.dart' as use_curly_braces;
import 'use_is_not_empty_test.dart' as use_is_not_empty;
@@ -52,7 +55,9 @@
remove_empty_constructor_body.main();
remove_empty_else.main();
remove_empty_statement.main();
+ remove_method_declaration.main();
remove_operator.main();
+ remove_this_expression.main();
remove_type_annotation.main();
remove_unnecessary_const.main();
remove_unnecessary_new.main();
@@ -60,6 +65,7 @@
replace_colon_with_equals.main();
replace_null_with_closure.main();
replace_with_is_empty.main();
+ replace_with_tear_off.main();
replace_with_var.main();
use_curly_braces.main();
use_is_not_empty.main();
diff --git a/pkg/analysis_server/test/src/services/correction/fix/make_return_type_nullable_test.dart b/pkg/analysis_server/test/src/services/correction/fix/make_return_type_nullable_test.dart
new file mode 100644
index 0000000..6181ed4
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/make_return_type_nullable_test.dart
@@ -0,0 +1,150 @@
+// Copyright (c) 2018, 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:analysis_server/src/services/correction/fix.dart';
+import 'package:analyzer/src/dart/analysis/experiments.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'fix_processor.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(MakeReturnTypeNullableTest);
+ });
+}
+
+@reflectiveTest
+class MakeReturnTypeNullableTest extends FixProcessorTest {
+ @override
+ List<String> get experiments => [EnableString.non_nullable];
+
+ @override
+ FixKind get kind => DartFixKind.MAKE_RETURN_TYPE_NULLABLE;
+
+ Future<void> test_function_async() async {
+ await resolveTestUnit('''
+Future<String> f(String? s) async {
+ return s;
+}
+''');
+ await assertHasFix('''
+Future<String?> f(String? s) async {
+ return s;
+}
+''');
+ }
+
+ Future<void> test_function_asyncStar() async {
+ await resolveTestUnit('''
+Stream<String> f(String? s) async* {
+ yield s;
+}
+''');
+ await assertHasFix('''
+Stream<String?> f(String? s) async* {
+ yield s;
+}
+''');
+ }
+
+ Future<void> test_function_sync() async {
+ await resolveTestUnit('''
+String f(String? s) {
+ return s;
+}
+''');
+ await assertHasFix('''
+String? f(String? s) {
+ return s;
+}
+''');
+ }
+
+ Future<void> test_function_syncStar() async {
+ await resolveTestUnit('''
+Iterable<String> f(String? s) sync* {
+ yield s;
+}
+''');
+ await assertHasFix('''
+Iterable<String?> f(String? s) sync* {
+ yield s;
+}
+''');
+ }
+
+ Future<void> test_getter_sync() async {
+ await resolveTestUnit('''
+class C {
+ String? f;
+ String get g => f;
+}
+''');
+ await assertHasFix('''
+class C {
+ String? f;
+ String? get g => f;
+}
+''');
+ }
+
+ Future<void> test_incompatibilityIsNotLimitedToNullability() async {
+ await resolveTestUnit('''
+int f() {
+ return '';
+}
+''');
+ await assertNoFix();
+ }
+
+ Future<void> test_localFunction_sync() async {
+ await resolveTestUnit('''
+void f() {
+ String g(String? s) {
+ return s;
+ }
+ g(null);
+}
+''');
+ await assertHasFix('''
+void f() {
+ String? g(String? s) {
+ return s;
+ }
+ g(null);
+}
+''');
+ }
+
+ Future<void> test_method_sync() async {
+ await resolveTestUnit('''
+class C {
+ String m(String? s) {
+ return s;
+ }
+}
+''');
+ await assertHasFix('''
+class C {
+ String? m(String? s) {
+ return s;
+ }
+}
+''');
+ }
+
+ Future<void> test_returnTypeHasTypeArguments() async {
+ await resolveTestUnit('''
+List<String> f() {
+ return null;
+}
+''');
+ await assertHasFix('''
+List<String>? f() {
+ return null;
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/remove_this_expression_test.dart b/pkg/analysis_server/test/src/services/correction/fix/remove_this_expression_test.dart
index a9e07f1..8949517 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/remove_this_expression_test.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/remove_this_expression_test.dart
@@ -55,23 +55,6 @@
''');
}
- Future<void> test_methodInvocation_twoCharactersOperator() async {
- await resolveTestUnit('''
-class A {
- void foo() {
- this?.foo();
- }
-}
-''');
- await assertHasFix('''
-class A {
- void foo() {
- foo();
- }
-}
-''');
- }
-
Future<void> test_propertyAccess_oneCharacterOperator() async {
await resolveTestUnit('''
class A {
@@ -90,23 +73,4 @@
}
''');
}
-
- Future<void> test_propertyAccess_twoCharactersOperator() async {
- await resolveTestUnit('''
-class A {
- int x;
- void foo() {
- this?.x = 2;
- }
-}
-''');
- await assertHasFix('''
-class A {
- int x;
- void foo() {
- x = 2;
- }
-}
-''');
- }
}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/replace_with_not_null_aware_test.dart b/pkg/analysis_server/test/src/services/correction/fix/replace_with_not_null_aware_test.dart
new file mode 100644
index 0000000..64b71ef
--- /dev/null
+++ b/pkg/analysis_server/test/src/services/correction/fix/replace_with_not_null_aware_test.dart
@@ -0,0 +1,153 @@
+// Copyright (c) 2020, 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:analysis_server/src/services/correction/fix.dart';
+import 'package:analyzer_plugin/utilities/fixes/fixes.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import 'fix_processor.dart';
+
+void main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(ReplaceWithNotNullAwareTest);
+ });
+}
+
+@reflectiveTest
+class ReplaceWithNotNullAwareTest extends FixProcessorTest {
+ @override
+ List<String> get experiments => ['non-nullable'];
+
+ @override
+ FixKind get kind => DartFixKind.REPLACE_WITH_NOT_NULL_AWARE;
+
+ Future<void> test_getter_cascade() async {
+ await resolveTestUnit('''
+void f(String s) {
+ s?..length;
+}
+''');
+ await assertHasFix('''
+void f(String s) {
+ s..length;
+}
+''');
+ }
+
+ Future<void> test_getter_simple() async {
+ await resolveTestUnit('''
+void f(String s) {
+ s?.length;
+}
+''');
+ await assertHasFix('''
+void f(String s) {
+ s.length;
+}
+''');
+ }
+
+ Future<void> test_index_cascade() async {
+ await resolveTestUnit('''
+void f(List<int> x) {
+ x?..[0];
+}
+''');
+ await assertHasFix('''
+void f(List<int> x) {
+ x..[0];
+}
+''');
+ }
+
+ Future<void> test_index_simple() async {
+ await resolveTestUnit('''
+void f(List<int> x) {
+ x?[0];
+}
+''');
+ await assertHasFix('''
+void f(List<int> x) {
+ x[0];
+}
+''');
+ }
+
+ Future<void> test_method_cascade() async {
+ await resolveTestUnit('''
+void f(String s) {
+ s?..indexOf('a');
+}
+''');
+ await assertHasFix('''
+void f(String s) {
+ s..indexOf('a');
+}
+''');
+ }
+
+ Future<void> test_method_simple() async {
+ await resolveTestUnit('''
+void f(String s) {
+ s?.indexOf('a');
+}
+''');
+ await assertHasFix('''
+void f(String s) {
+ s.indexOf('a');
+}
+''');
+ }
+
+ Future<void> test_setter_cascade() async {
+ await resolveTestUnit('''
+void f(C c) {
+ c?..s = 0;
+}
+class C {
+ set s(int x) {}
+}
+''');
+ await assertHasFix('''
+void f(C c) {
+ c..s = 0;
+}
+class C {
+ set s(int x) {}
+}
+''');
+ }
+
+ Future<void> test_setter_simple() async {
+ await resolveTestUnit('''
+void f(C c) {
+ c?.s = 0;
+}
+class C {
+ set s(int x) {}
+}
+''');
+ await assertHasFix('''
+void f(C c) {
+ c.s = 0;
+}
+class C {
+ set s(int x) {}
+}
+''');
+ }
+
+ Future<void> test_spread() async {
+ await resolveTestUnit('''
+void f(List<int> x) {
+ [...?x];
+}
+''');
+ await assertHasFix('''
+void f(List<int> x) {
+ [...x];
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/test/src/services/correction/fix/test_all.dart b/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
index a65ca4c..64dde02 100644
--- a/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
+++ b/pkg/analysis_server/test/src/services/correction/fix/test_all.dart
@@ -92,6 +92,7 @@
import 'make_class_abstract_test.dart' as make_class_abstract;
import 'make_field_not_final_test.dart' as make_field_not_final;
import 'make_final_test.dart' as make_final;
+import 'make_return_type_nullable_test.dart' as make_return_type_nullable;
import 'make_variable_not_final_test.dart' as make_variable_not_final;
import 'move_type_arguments_to_class_test.dart' as move_type_arguments_to_class;
import 'organize_imports_test.dart' as organize_imports;
@@ -151,6 +152,7 @@
import 'replace_with_interpolation_test.dart' as replace_with_interpolation;
import 'replace_with_is_empty_test.dart' as replace_with_is_empty;
import 'replace_with_is_not_empty_test.dart' as replace_with_is_not_empty;
+import 'replace_with_not_null_aware_test.dart' as replace_with_not_null_aware;
import 'replace_with_null_aware_test.dart' as replace_with_null_aware;
import 'replace_with_tear_off_test.dart' as replace_with_tear_off;
import 'replace_with_var_test.dart' as replace_with_var;
@@ -245,6 +247,7 @@
make_class_abstract.main();
make_field_not_final.main();
make_final.main();
+ make_return_type_nullable.main();
make_variable_not_final.main();
move_type_arguments_to_class.main();
organize_imports.main();
@@ -300,6 +303,7 @@
replace_with_interpolation.main();
replace_with_is_empty.main();
replace_with_is_not_empty.main();
+ replace_with_not_null_aware.main();
replace_with_null_aware.main();
replace_with_tear_off.main();
replace_with_var.main();
diff --git a/pkg/analysis_server/tool/completion_metrics/code_metrics.dart b/pkg/analysis_server/tool/completion_metrics/code_metrics.dart
index cd29795..d0baded 100644
--- a/pkg/analysis_server/tool/completion_metrics/code_metrics.dart
+++ b/pkg/analysis_server/tool/completion_metrics/code_metrics.dart
@@ -563,6 +563,7 @@
_visitChildren(node, {
'documentationComment': node.documentationComment,
'metadata': node.metadata,
+ 'abstractKeyword': node.abstractKeyword,
'covariantKeyword': node.covariantKeyword,
'staticKeyword': node.staticKeyword,
'fields': node.fields,
diff --git a/pkg/analysis_server/tool/completion_metrics/visitors.dart b/pkg/analysis_server/tool/completion_metrics/visitors.dart
index f154a6d..cc8d5ff 100644
--- a/pkg/analysis_server/tool/completion_metrics/visitors.dart
+++ b/pkg/analysis_server/tool/completion_metrics/visitors.dart
@@ -347,6 +347,7 @@
@override
void visitFieldDeclaration(FieldDeclaration node) {
+ safelyRecordKeywordCompletion(node.abstractKeyword);
safelyRecordKeywordCompletion(node.covariantKeyword);
safelyRecordKeywordCompletion(node.staticKeyword);
return super.visitFieldDeclaration(node);
diff --git a/pkg/analysis_server/tool/lsp_spec/README.md b/pkg/analysis_server/tool/lsp_spec/README.md
index bba94d6..41df728 100644
--- a/pkg/analysis_server/tool/lsp_spec/README.md
+++ b/pkg/analysis_server/tool/lsp_spec/README.md
@@ -111,6 +111,14 @@
Starts the analzyer diagnostics server (if not already running) and returns the port number it's listening on.
+### dart/reanalyze Method
+
+Direction: Client -> Server
+Params: None
+Returns: None
+
+Forces re-reading of all potentially changed files, re-resolving of all referenced URIs, and corresponding re-analysis of everything affected in the current analysis roots. Clients should not usually need to call this method - needing to do so may indicate a bug in the server.
+
### dart/textDocument/super Method
Direction: Client -> Server
diff --git a/pkg/analyzer/lib/dart/ast/ast.dart b/pkg/analyzer/lib/dart/ast/ast.dart
index fb1492f..0ecf87a 100644
--- a/pkg/analyzer/lib/dart/ast/ast.dart
+++ b/pkg/analyzer/lib/dart/ast/ast.dart
@@ -2131,7 +2131,19 @@
/// The declaration of one or more fields of the same type.
///
/// fieldDeclaration ::=
-/// 'static'? [VariableDeclarationList] ';'
+/// 'static' 'const' <type>? <staticFinalDeclarationList>
+/// | 'static' 'final' <type>? <staticFinalDeclarationList>
+/// | 'static' 'late' 'final' <type>? <initializedIdentifierList>
+/// | 'static' 'late'? <varOrType> <initializedIdentifierList>
+/// | 'covariant' 'late'? <varOrType> <initializedIdentifierList>
+/// | 'late'? 'final' <type>? <initializedIdentifierList>
+/// | 'late'? <varOrType> <initializedIdentifierList>
+/// | 'abstract' (<finalVarOrType> | 'covariant' <varOrType>)
+/// <identifierList>
+///
+/// (Note: there is no <fieldDeclaration> production in the grammar; this is a
+/// subset of the grammar production <declaration>, which encompasses everything
+/// that can appear inside a class declaration except methods).
///
/// Prior to the 'extension-methods' experiment, these nodes were always
/// children of a class declaration. When the experiment is enabled, these nodes
@@ -2139,6 +2151,9 @@
///
/// Clients may not extend, implement or mix-in this class.
abstract class FieldDeclaration implements ClassMember {
+ /// The `abstract` keyword, or `null` if the keyword was not used.
+ Token get abstractKeyword;
+
/// The 'covariant' keyword, or `null` if the keyword was not used.
Token get covariantKeyword;
diff --git a/pkg/analyzer/lib/dart/ast/ast_factory.dart b/pkg/analyzer/lib/dart/ast/ast_factory.dart
index d324d7a..231ad4c 100644
--- a/pkg/analyzer/lib/dart/ast/ast_factory.dart
+++ b/pkg/analyzer/lib/dart/ast/ast_factory.dart
@@ -363,6 +363,7 @@
FieldDeclaration fieldDeclaration2(
{Comment comment,
List<Annotation> metadata,
+ Token abstractKeyword,
Token covariantKeyword,
Token staticKeyword,
@required VariableDeclarationList fieldList,
diff --git a/pkg/analyzer/lib/dart/element/element.dart b/pkg/analyzer/lib/dart/element/element.dart
index 12f85cc..34e6cd6 100644
--- a/pkg/analyzer/lib/dart/element/element.dart
+++ b/pkg/analyzer/lib/dart/element/element.dart
@@ -1110,6 +1110,10 @@
@override
FieldElement get declaration;
+ /// Return `true` if this field is abstract. Executable fields are abstract if
+ /// they are declared with the `abstract` keyword.
+ bool get isAbstract;
+
/// Return `true` if this field was explicitly marked as being covariant.
bool get isCovariant;
diff --git a/pkg/analyzer/lib/error/error.dart b/pkg/analyzer/lib/error/error.dart
index e5f3230..a0780e0 100644
--- a/pkg/analyzer/lib/error/error.dart
+++ b/pkg/analyzer/lib/error/error.dart
@@ -60,6 +60,8 @@
AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES,
AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITHOUT_VALUES,
AnalysisOptionsWarningCode.UNSUPPORTED_VALUE,
+ CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER,
+ CompileTimeErrorCode.ABSTRACT_FIELD_INITIALIZER,
CompileTimeErrorCode.ABSTRACT_SUPER_MEMBER_REFERENCE,
CompileTimeErrorCode.ACCESS_PRIVATE_ENUM_FIELD,
CompileTimeErrorCode.AMBIGUOUS_EXPORT,
diff --git a/pkg/analyzer/lib/src/dart/analysis/analysis_context_collection.dart b/pkg/analyzer/lib/src/dart/analysis/analysis_context_collection.dart
index d2ae5c0..6fea185 100644
--- a/pkg/analyzer/lib/src/dart/analysis/analysis_context_collection.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/analysis_context_collection.dart
@@ -5,6 +5,7 @@
import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
import 'package:analyzer/dart/analysis/context_locator.dart';
+import 'package:analyzer/dart/analysis/declared_variables.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/dart/analysis/context_builder.dart';
@@ -21,13 +22,14 @@
final List<AnalysisContext> contexts = [];
/// Initialize a newly created analysis context manager.
- AnalysisContextCollectionImpl(
- {bool enableIndex = false,
- @required List<String> includedPaths,
- List<String> excludedPaths,
- ResourceProvider resourceProvider,
- String sdkPath})
- : resourceProvider =
+ AnalysisContextCollectionImpl({
+ Map<String, String> declaredVariables,
+ bool enableIndex = false,
+ @required List<String> includedPaths,
+ List<String> excludedPaths,
+ ResourceProvider resourceProvider,
+ String sdkPath,
+ }) : resourceProvider =
resourceProvider ?? PhysicalResourceProvider.INSTANCE {
sdkPath ??= getSdkPath();
@@ -49,6 +51,7 @@
);
var context = contextBuilder.createContext(
contextRoot: root,
+ declaredVariables: DeclaredVariables.fromMap(declaredVariables ?? {}),
enableIndex: enableIndex,
sdkPath: sdkPath,
);
diff --git a/pkg/analyzer/lib/src/dart/analysis/file_state.dart b/pkg/analyzer/lib/src/dart/analysis/file_state.dart
index 9faa830..d288490 100644
--- a/pkg/analyzer/lib/src/dart/analysis/file_state.dart
+++ b/pkg/analyzer/lib/src/dart/analysis/file_state.dart
@@ -852,7 +852,9 @@
// Create a new file.
FileSource uriSource = FileSource(resource, uri);
WorkspacePackage workspacePackage = _workspace?.findPackageFor(path);
- FeatureSet featureSet = featureSetProvider.getFeatureSet(path, uri);
+ FeatureSet workspacePackageFeatureSet = workspacePackage?.featureSet;
+ FeatureSet featureSet = workspacePackageFeatureSet ??
+ featureSetProvider.getFeatureSet(path, uri);
Version packageLanguageVersion =
featureSetProvider.getLanguageVersion(path, uri);
file = FileState._(this, path, uri, uriSource, workspacePackage,
@@ -896,7 +898,9 @@
File resource = _resourceProvider.getFile(path);
FileSource source = FileSource(resource, uri);
WorkspacePackage workspacePackage = _workspace?.findPackageFor(path);
- FeatureSet featureSet = featureSetProvider.getFeatureSet(path, uri);
+ FeatureSet workspacePackageFeatureSet = workspacePackage?.featureSet;
+ FeatureSet featureSet = workspacePackageFeatureSet ??
+ featureSetProvider.getFeatureSet(path, uri);
Version packageLanguageVersion =
featureSetProvider.getLanguageVersion(path, uri);
file = FileState._(this, path, uri, source, workspacePackage, featureSet,
diff --git a/pkg/analyzer/lib/src/dart/ast/ast.dart b/pkg/analyzer/lib/src/dart/ast/ast.dart
index 4fbd468..bfbf152 100644
--- a/pkg/analyzer/lib/src/dart/ast/ast.dart
+++ b/pkg/analyzer/lib/src/dart/ast/ast.dart
@@ -3920,6 +3920,9 @@
/// fieldDeclaration ::=
/// 'static'? [VariableDeclarationList] ';'
class FieldDeclarationImpl extends ClassMemberImpl implements FieldDeclaration {
+ @override
+ Token abstractKeyword;
+
/// The 'covariant' keyword, or `null` if the keyword was not used.
@override
Token covariantKeyword;
@@ -3943,6 +3946,7 @@
FieldDeclarationImpl(
CommentImpl comment,
List<Annotation> metadata,
+ this.abstractKeyword,
this.covariantKeyword,
this.staticKeyword,
VariableDeclarationListImpl fieldList,
@@ -3971,7 +3975,9 @@
@override
Token get firstTokenAfterCommentAndMetadata {
- if (covariantKeyword != null) {
+ if (abstractKeyword != null) {
+ return abstractKeyword;
+ } else if (covariantKeyword != null) {
return covariantKeyword;
} else if (staticKeyword != null) {
return staticKeyword;
diff --git a/pkg/analyzer/lib/src/dart/ast/ast_factory.dart b/pkg/analyzer/lib/src/dart/ast/ast_factory.dart
index f60676c..ad2b6d8 100644
--- a/pkg/analyzer/lib/src/dart/ast/ast_factory.dart
+++ b/pkg/analyzer/lib/src/dart/ast/ast_factory.dart
@@ -394,18 +394,19 @@
VariableDeclarationList fieldList,
Token semicolon) =>
FieldDeclarationImpl(
- comment, metadata, null, staticKeyword, fieldList, semicolon);
+ comment, metadata, null, null, staticKeyword, fieldList, semicolon);
@override
FieldDeclaration fieldDeclaration2(
{Comment comment,
List<Annotation> metadata,
+ Token abstractKeyword,
Token covariantKeyword,
Token staticKeyword,
@required VariableDeclarationList fieldList,
@required Token semicolon}) =>
- FieldDeclarationImpl(comment, metadata, covariantKeyword, staticKeyword,
- fieldList, semicolon);
+ FieldDeclarationImpl(comment, metadata, abstractKeyword, covariantKeyword,
+ staticKeyword, fieldList, semicolon);
@override
FieldFormalParameter fieldFormalParameter(
diff --git a/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart b/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart
index adf8d2b..eba0b8c 100644
--- a/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart
+++ b/pkg/analyzer/lib/src/dart/ast/to_source_visitor.dart
@@ -495,6 +495,7 @@
@override
void visitFieldDeclaration(FieldDeclaration node) {
safelyVisitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
+ safelyVisitTokenWithSuffix(node.abstractKeyword, " ");
safelyVisitTokenWithSuffix(node.staticKeyword, " ");
safelyVisitNode(node.fields);
sink.write(";");
diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart
index 3867938..7d27356 100644
--- a/pkg/analyzer/lib/src/dart/ast/utilities.dart
+++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart
@@ -447,6 +447,7 @@
astFactory.fieldDeclaration2(
comment: cloneNode(node.documentationComment),
metadata: cloneNodeList(node.metadata),
+ abstractKeyword: cloneToken(node.abstractKeyword),
covariantKeyword: cloneToken(node.covariantKeyword),
staticKeyword: cloneToken(node.staticKeyword),
fieldList: cloneNode(node.fields),
@@ -1573,8 +1574,9 @@
@override
bool visitFieldDeclaration(FieldDeclaration node) {
FieldDeclaration other = _other as FieldDeclaration;
- return isEqualNodes(
- node.documentationComment, other.documentationComment) &&
+ return isEqualTokens(node.abstractKeyword, other.abstractKeyword) &&
+ isEqualTokens(node.covariantKeyword, other.covariantKeyword) &&
+ isEqualNodes(node.documentationComment, other.documentationComment) &&
_isEqualNodeLists(node.metadata, other.metadata) &&
isEqualTokens(node.staticKeyword, other.staticKeyword) &&
isEqualNodes(node.fields, other.fields) &&
@@ -4462,6 +4464,7 @@
bool visitFieldDeclaration(FieldDeclaration node) {
FieldDeclaration toNode = _toNode as FieldDeclaration;
return _and(
+ _isEqualTokens(node.abstractKeyword, toNode.abstractKeyword),
_isEqualNodes(node.documentationComment, toNode.documentationComment),
_isEqualNodeLists(node.metadata, toNode.metadata),
_isEqualTokens(node.staticKeyword, toNode.staticKeyword),
diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart
index 8cc2292..a102215 100644
--- a/pkg/analyzer/lib/src/dart/element/element.dart
+++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -4269,6 +4269,14 @@
FieldElement get declaration => this;
@override
+ bool get isAbstract {
+ if (linkedNode != null) {
+ return enclosingUnit.linkedContext.isAbstract(linkedNode);
+ }
+ return hasModifier(Modifier.ABSTRACT);
+ }
+
+ @override
bool get isCovariant {
if (linkedNode != null) {
return linkedContext.isExplicitlyCovariant(linkedNode);
@@ -7020,6 +7028,7 @@
{Reference reference})
: super(variable.name, variable.nameOffset, reference: reference) {
this.variable = variable;
+ isAbstract = variable is FieldElementImpl && variable.isAbstract;
isStatic = variable.isStatic;
isSynthetic = true;
}
diff --git a/pkg/analyzer/lib/src/dart/element/member.dart b/pkg/analyzer/lib/src/dart/element/member.dart
index d97532c..8385169 100644
--- a/pkg/analyzer/lib/src/dart/element/member.dart
+++ b/pkg/analyzer/lib/src/dart/element/member.dart
@@ -334,6 +334,9 @@
}
@override
+ bool get isAbstract => declaration.isAbstract;
+
+ @override
bool get isCovariant => declaration.isCovariant;
@override
diff --git a/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart b/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart
index bd7cb0b..a029dc9 100644
--- a/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart
+++ b/pkg/analyzer/lib/src/dart/micro/library_analyzer.dart
@@ -125,7 +125,7 @@
});
// Resolve URIs in directives to corresponding sources.
- FeatureSet featureSet = units[_library].featureSet;
+ FeatureSet featureSet = units.values.first.featureSet;
performance.run('resolveUriDirectives', (performance) {
units.forEach((file, unit) {
@@ -139,7 +139,7 @@
});
performance.run('resolveDirectives', (performance) {
- _resolveDirectives(units, forCompletion);
+ _resolveDirectives(units, completionPath);
});
performance.run('resolveFiles', (performance) {
@@ -529,15 +529,17 @@
void _resolveDirectives(
Map<FileState, CompilationUnit> units,
- bool forCompletion,
+ String completionPath,
) {
- CompilationUnit definingCompilationUnit = units[_library];
- definingCompilationUnit.element = _libraryElement.definingCompilationUnit;
-
- if (forCompletion) {
+ if (completionPath != null) {
+ var completionUnit = units.values.first;
+ completionUnit.element = _unitElementWithPath(completionPath);
return;
}
+ CompilationUnit definingCompilationUnit = units[_library];
+ definingCompilationUnit.element = _libraryElement.definingCompilationUnit;
+
bool matchNodeElement(Directive node, Element element) {
return node.keyword.offset == element.nameOffset;
}
@@ -757,6 +759,15 @@
}
}
+ CompilationUnitElement _unitElementWithPath(String path) {
+ for (var unitElement in _libraryElement.units) {
+ if (unitElement.source.fullName == path) {
+ return unitElement;
+ }
+ }
+ return null;
+ }
+
/// Validate that the feature set associated with the compilation [unit] is
/// the same as the [expectedSet] of features supported by the library.
void _validateFeatureSet(CompilationUnit unit, FeatureSet expectedSet) {
diff --git a/pkg/analyzer/lib/src/dart/sdk/sdk.dart b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
index 29956ee..28a8cd2 100644
--- a/pkg/analyzer/lib/src/dart/sdk/sdk.dart
+++ b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
@@ -219,7 +219,7 @@
Version languageVersion,
}) {
this.resourceProvider = resourceProvider;
- this._languageVersion =
+ _languageVersion =
languageVersion ?? languageVersionFromSdkVersion(io.Platform.version);
embedderYamls?.forEach(_processEmbedderYaml);
}
diff --git a/pkg/analyzer/lib/src/error/codes.dart b/pkg/analyzer/lib/src/error/codes.dart
index d612589..b4f23ee 100644
--- a/pkg/analyzer/lib/src/error/codes.dart
+++ b/pkg/analyzer/lib/src/error/codes.dart
@@ -22,6 +22,19 @@
* when appropriate, how the problem can be corrected.
*/
class CompileTimeErrorCode extends AnalyzerErrorCode {
+ static const CompileTimeErrorCode ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER =
+ CompileTimeErrorCode('ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER',
+ 'Abstract fields cannot have initializers.',
+ correction:
+ "Try removing the field initializer or the 'abstract' keyword "
+ "from the field declaration.");
+
+ static const CompileTimeErrorCode ABSTRACT_FIELD_INITIALIZER =
+ CompileTimeErrorCode('ABSTRACT_FIELD_INITIALIZER',
+ 'Abstract fields cannot have initializers.',
+ correction:
+ "Try removing the initializer or the 'abstract' keyword.");
+
/**
* Parameters:
* 0: the display name for the kind of the found abstract member
diff --git a/pkg/analyzer/lib/src/error/constructor_fields_verifier.dart b/pkg/analyzer/lib/src/error/constructor_fields_verifier.dart
index d500cff..f28b925 100644
--- a/pkg/analyzer/lib/src/error/constructor_fields_verifier.dart
+++ b/pkg/analyzer/lib/src/error/constructor_fields_verifier.dart
@@ -80,6 +80,7 @@
_fieldMap.forEach((FieldElement field, _InitState state) {
if (state != _InitState.notInit) return;
if (field.isLate) return;
+ if (field.isAbstract) return;
if (field.isFinal) {
notInitFinalFields.add(field);
diff --git a/pkg/analyzer/lib/src/error/inheritance_override.dart b/pkg/analyzer/lib/src/error/inheritance_override.dart
index 4adca2d..cac6440 100644
--- a/pkg/analyzer/lib/src/error/inheritance_override.dart
+++ b/pkg/analyzer/lib/src/error/inheritance_override.dart
@@ -581,18 +581,33 @@
/// because the class itself defines an abstract method with this [name],
/// report the more specific error, and return `true`.
bool _reportConcreteClassWithAbstractMember(String name) {
+ bool checkMemberNameCombo(ClassMember member, String memberName) {
+ if (memberName == name) {
+ reporter.reportErrorForNode(
+ CompileTimeErrorCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
+ member,
+ [name, classElement.name]);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
for (var member in members) {
if (member is MethodDeclaration) {
var name2 = member.name.name;
if (member.isSetter) {
name2 += '=';
}
- if (name2 == name) {
- reporter.reportErrorForNode(
- CompileTimeErrorCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
- member,
- [name, classElement.name]);
- return true;
+ if (checkMemberNameCombo(member, name2)) return true;
+ } else if (member is FieldDeclaration) {
+ for (var variableDeclaration in member.fields.variables) {
+ var name2 = variableDeclaration.name.name;
+ if (checkMemberNameCombo(member, name2)) return true;
+ if (!variableDeclaration.isFinal) {
+ name2 += '=';
+ if (checkMemberNameCombo(member, name2)) return true;
+ }
}
}
}
diff --git a/pkg/analyzer/lib/src/fasta/ast_builder.dart b/pkg/analyzer/lib/src/fasta/ast_builder.dart
index 2cf4091..42141c5 100644
--- a/pkg/analyzer/lib/src/fasta/ast_builder.dart
+++ b/pkg/analyzer/lib/src/fasta/ast_builder.dart
@@ -872,6 +872,7 @@
currentDeclarationMembers.add(ast.fieldDeclaration2(
comment: comment,
metadata: metadata,
+ abstractKeyword: abstractToken,
covariantKeyword: covariantKeyword,
staticKeyword: staticToken,
fieldList: variableList,
diff --git a/pkg/analyzer/lib/src/generated/error_verifier.dart b/pkg/analyzer/lib/src/generated/error_verifier.dart
index 98df2ee..4eb6d7d 100644
--- a/pkg/analyzer/lib/src/generated/error_verifier.dart
+++ b/pkg/analyzer/lib/src/generated/error_verifier.dart
@@ -491,6 +491,8 @@
_checkForInvalidField(node, fieldName, staticElement);
if (staticElement is FieldElement) {
_checkForFieldInitializerNotAssignable(node, staticElement);
+ _checkForAbstractFieldConstructorInitializer(
+ node.fieldName, staticElement);
}
super.visitConstructorFieldInitializer(node);
} finally {
@@ -599,6 +601,14 @@
_checkForPrivateOptionalParameter(node);
_checkForFieldInitializingFormalRedirectingConstructor(node);
_checkForTypeAnnotationDeferredClass(node.type);
+ ParameterElement element = node.declaredElement;
+ if (element is FieldFormalParameterElement) {
+ FieldElement fieldElement = element.field;
+ if (fieldElement != null) {
+ _checkForAbstractFieldConstructorInitializer(
+ node.identifier, fieldElement);
+ }
+ }
super.visitFieldFormalParameter(node);
}
@@ -1190,6 +1200,7 @@
// do checks
_checkForInvalidAssignment(nameNode, initializerNode);
_checkForImplicitDynamicIdentifier(node, nameNode);
+ _checkForAbstractFieldInitializer(node);
// visit name
nameNode.accept(this);
// visit initializer
@@ -1283,6 +1294,24 @@
}
}
+ void _checkForAbstractFieldConstructorInitializer(
+ AstNode node, FieldElement fieldElement) {
+ if (fieldElement.isAbstract) {
+ _errorReporter.reportErrorForNode(
+ CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER, node);
+ }
+ }
+
+ void _checkForAbstractFieldInitializer(VariableDeclaration node) {
+ var declaredElement = node.declaredElement;
+ if (declaredElement is FieldElement &&
+ declaredElement.isAbstract &&
+ node.initializer != null) {
+ _errorReporter.reportErrorForNode(
+ CompileTimeErrorCode.ABSTRACT_FIELD_INITIALIZER, node.name);
+ }
+ }
+
/// Verify that all classes of the given [withClause] are valid.
///
/// See [CompileTimeErrorCode.MIXIN_CLASS_DECLARES_CONSTRUCTOR],
@@ -2553,11 +2582,16 @@
CompileTimeErrorCode.CONST_NOT_INITIALIZED,
variable.name,
[variable.name.name]);
- } else if (!_isNonNullableByDefault || !variable.isLate) {
- _errorReporter.reportErrorForNode(
- CompileTimeErrorCode.FINAL_NOT_INITIALIZED,
- variable.name,
- [variable.name.name]);
+ } else {
+ var variableElement = variable.declaredElement;
+ if (variableElement is FieldElement && variableElement.isAbstract) {
+ // Abstract fields can't be initialized, so no error.
+ } else if (!_isNonNullableByDefault || !variable.isLate) {
+ _errorReporter.reportErrorForNode(
+ CompileTimeErrorCode.FINAL_NOT_INITIALIZED,
+ variable.name,
+ [variable.name.name]);
+ }
}
}
}
@@ -3531,9 +3565,11 @@
if (_isEnclosingClassFfiStruct) return;
for (var field in fields.variables) {
+ var fieldElement = field.declaredElement as FieldElement;
+ if (fieldElement.isAbstract) continue;
if (field.initializer != null) continue;
- var type = field.declaredElement.type;
+ var type = fieldElement.type;
if (!_typeSystem.isPotentiallyNonNullable(type)) continue;
_errorReporter.reportErrorForNode(
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index 0d0f8b1..d919f68 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -2910,7 +2910,7 @@
return;
}
// Prepare VariableElement.
- Element element = nameScope.lookupIdentifier(node);
+ Element element = nameScope.lookup2(node.name).getter;
if (element is! VariableElement) {
return;
}
diff --git a/pkg/analyzer/lib/src/generated/testing/ast_test_factory.dart b/pkg/analyzer/lib/src/generated/testing/ast_test_factory.dart
index b2e8b8a..662d1d3 100644
--- a/pkg/analyzer/lib/src/generated/testing/ast_test_factory.dart
+++ b/pkg/analyzer/lib/src/generated/testing/ast_test_factory.dart
@@ -516,8 +516,12 @@
argumentList: argumentList);
static FieldDeclaration fieldDeclaration(bool isStatic, Keyword keyword,
- TypeAnnotation type, List<VariableDeclaration> variables) =>
+ TypeAnnotation type, List<VariableDeclaration> variables,
+ {bool isAbstract = false}) =>
astFactory.fieldDeclaration2(
+ abstractKeyword: isAbstract
+ ? TokenFactory.tokenFromKeyword(Keyword.ABSTRACT)
+ : null,
staticKeyword:
isStatic ? TokenFactory.tokenFromKeyword(Keyword.STATIC) : null,
fieldList: variableDeclarationList(keyword, type, variables),
diff --git a/pkg/analyzer/lib/src/summary2/ast_binary_reader.dart b/pkg/analyzer/lib/src/summary2/ast_binary_reader.dart
index b029847..8a64bc2 100644
--- a/pkg/analyzer/lib/src/summary2/ast_binary_reader.dart
+++ b/pkg/analyzer/lib/src/summary2/ast_binary_reader.dart
@@ -649,6 +649,8 @@
FieldDeclaration _read_fieldDeclaration(LinkedNode data) {
var node = astFactory.fieldDeclaration2(
comment: _readDocumentationComment(data),
+ abstractKeyword:
+ AstBinaryFlags.isAbstract(data.flags) ? _Tokens.ABSTRACT : null,
covariantKeyword:
AstBinaryFlags.isCovariant(data.flags) ? _Tokens.COVARIANT : null,
fieldList: _readNode(data.fieldDeclaration_fields),
diff --git a/pkg/analyzer/lib/src/summary2/ast_binary_writer.dart b/pkg/analyzer/lib/src/summary2/ast_binary_writer.dart
index f8bdeee..1e8276a 100644
--- a/pkg/analyzer/lib/src/summary2/ast_binary_writer.dart
+++ b/pkg/analyzer/lib/src/summary2/ast_binary_writer.dart
@@ -554,6 +554,7 @@
informativeId: getInformativeId(node),
);
builder.flags = AstBinaryFlags.encode(
+ isAbstract: node.abstractKeyword != null,
isCovariant: node.covariantKeyword != null,
isStatic: node.staticKeyword != null,
);
diff --git a/pkg/analyzer/lib/src/summary2/ast_text_printer.dart b/pkg/analyzer/lib/src/summary2/ast_text_printer.dart
index 0cd8fa6..9276295 100644
--- a/pkg/analyzer/lib/src/summary2/ast_text_printer.dart
+++ b/pkg/analyzer/lib/src/summary2/ast_text_printer.dart
@@ -357,6 +357,7 @@
void visitFieldDeclaration(FieldDeclaration node) {
_classMember(node);
_token(node.staticKeyword);
+ _token(node.abstractKeyword);
_token(node.covariantKeyword);
node.fields.accept(this);
_token(node.semicolon);
diff --git a/pkg/analyzer/lib/src/summary2/linked_unit_context.dart b/pkg/analyzer/lib/src/summary2/linked_unit_context.dart
index 0a34140..b7bae75 100644
--- a/pkg/analyzer/lib/src/summary2/linked_unit_context.dart
+++ b/pkg/analyzer/lib/src/summary2/linked_unit_context.dart
@@ -769,6 +769,20 @@
return false;
} else if (node is MethodDeclaration) {
return LazyMethodDeclaration.isAbstract(node);
+ } else if (node is VariableDeclaration) {
+ var parent = node.parent;
+ if (parent is VariableDeclarationList) {
+ var grandParent = parent.parent;
+ if (grandParent is FieldDeclaration) {
+ return grandParent.abstractKeyword != null;
+ } else {
+ throw UnimplementedError('${grandParent.runtimeType}');
+ }
+ } else {
+ throw UnimplementedError('${parent.runtimeType}');
+ }
+ } else if (node is EnumConstantDeclaration) {
+ return false;
}
throw UnimplementedError('${node.runtimeType}');
}
diff --git a/pkg/analyzer/lib/src/test_utilities/resource_provider_mixin.dart b/pkg/analyzer/lib/src/test_utilities/resource_provider_mixin.dart
index b02dfaf..13aee9b 100644
--- a/pkg/analyzer/lib/src/test_utilities/resource_provider_mixin.dart
+++ b/pkg/analyzer/lib/src/test_utilities/resource_provider_mixin.dart
@@ -55,11 +55,6 @@
return resourceProvider.newFile(convertedPath, content);
}
- File newFileWithBytes(String path, List<int> bytes) {
- String convertedPath = convertPath(path);
- return resourceProvider.newFileWithBytes(convertedPath, bytes);
- }
-
Folder newFolder(String path) {
String convertedPath = convertPath(path);
return resourceProvider.newFolder(convertedPath);
diff --git a/pkg/analyzer/lib/src/workspace/bazel.dart b/pkg/analyzer/lib/src/workspace/bazel.dart
index 18b35fdd8..47f1790 100644
--- a/pkg/analyzer/lib/src/workspace/bazel.dart
+++ b/pkg/analyzer/lib/src/workspace/bazel.dart
@@ -5,7 +5,9 @@
import 'dart:collection';
import 'dart:core';
+import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/file_system/file_system.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -483,10 +485,44 @@
@override
final BazelWorkspace workspace;
+ bool _featureSetReady = false;
+ FeatureSet _featureSet;
+
BazelWorkspacePackage(String packageName, this.root, this.workspace)
: _uriPrefix = 'package:$packageName/';
@override
+ FeatureSet get featureSet {
+ if (_featureSetReady) {
+ return _featureSet;
+ }
+
+ try {
+ _featureSetReady = true;
+ var buildContent = workspace.provider
+ .getFolder(root)
+ .getChildAssumingFile('BUILD')
+ .readAsStringSync();
+ var hasNonNullableFlag = buildContent
+ .split('\n')
+ .map((e) => e.trim())
+ .where((e) => !e.startsWith('#'))
+ .map((e) => e.replaceAll(' ', ''))
+ .join()
+ .contains('dart_package(null_safety=True');
+ if (hasNonNullableFlag) {
+ _featureSet = FeatureSet.fromEnableFlags(
+ [EnableString.non_nullable],
+ );
+ }
+ } on FileSystemException {
+ // ignored
+ }
+
+ return _featureSet;
+ }
+
+ @override
bool contains(Source source) {
if (source.uri.isScheme('package')) {
return source.uri.toString().startsWith(_uriPrefix);
diff --git a/pkg/analyzer/lib/src/workspace/package_build.dart b/pkg/analyzer/lib/src/workspace/package_build.dart
index d274ccb..39fdaaf 100644
--- a/pkg/analyzer/lib/src/workspace/package_build.dart
+++ b/pkg/analyzer/lib/src/workspace/package_build.dart
@@ -152,13 +152,25 @@
/// matches the behavior of package:build.
final String projectPackageName;
+ /// `.dart_tool/build/generated` in [root].
+ final String generatedRootPath;
+
+ /// [projectPackageName] in [generatedRootPath].
+ final String generatedThisPath;
+
/// The singular package in this workspace.
///
/// Each "package:build" workspace is itself one package.
PackageBuildWorkspacePackage _theOnlyPackage;
PackageBuildWorkspace._(
- this.provider, this._packageMap, this.root, this.projectPackageName);
+ this.provider,
+ this._packageMap,
+ this.root,
+ this.projectPackageName,
+ this.generatedRootPath,
+ this.generatedThisPath,
+ );
@override
UriResolver get packageUriResolver => PackageBuildPackageUriResolver(
@@ -231,15 +243,22 @@
}
@override
- WorkspacePackage findPackageFor(String filePath) {
- path.Context context = provider.pathContext;
- final folder = provider.getFolder(context.dirname(filePath));
- if (context.isWithin(root, folder.path)) {
- _theOnlyPackage ??= PackageBuildWorkspacePackage(root, this);
- return _theOnlyPackage;
- } else {
+ WorkspacePackage findPackageFor(String path) {
+ var pathContext = provider.pathContext;
+
+ // Must be in this workspace.
+ if (!pathContext.isWithin(root, path)) {
return null;
}
+
+ // If generated, must be for this package.
+ if (pathContext.isWithin(generatedRootPath, path)) {
+ if (!pathContext.isWithin(generatedThisPath, path)) {
+ return null;
+ }
+ }
+
+ return _theOnlyPackage ??= PackageBuildWorkspacePackage(root, this);
}
/// Find the package:build workspace that contains the given [filePath].
@@ -265,8 +284,13 @@
if (dartToolBuildDir.exists && pubspec.exists) {
try {
final yaml = loadYaml(pubspec.readAsStringSync());
- return PackageBuildWorkspace._(
- provider, packageMap, folder.path, yaml['name']);
+ final packageName = yaml['name'] as String;
+ final generatedRootPath = provider.pathContext
+ .join(folder.path, '.dart_tool', 'build', 'generated');
+ final generatedThisPath =
+ provider.pathContext.join(generatedRootPath, packageName);
+ return PackageBuildWorkspace._(provider, packageMap, folder.path,
+ packageName, generatedRootPath, generatedThisPath);
} catch (_) {}
}
@@ -292,12 +316,18 @@
@override
bool contains(Source source) {
- String filePath = filePathFromSource(source);
- if (filePath == null) return false;
- // There is a 1-1 relationship between PackageBuildWorkspaces and
- // PackageBuildWorkspacePackages. If a file is in a package's workspace,
- // then it is in the package as well.
- return workspace.provider.pathContext.isWithin(workspace.root, filePath) &&
- workspace.findFile(filePath) != null;
+ var uri = source.uri;
+
+ if (uri.isScheme('package')) {
+ var packageName = uri.pathSegments[0];
+ return packageName == workspace.projectPackageName;
+ }
+
+ if (uri.isScheme('file')) {
+ var path = source.fullName;
+ return workspace.findPackageFor(path) != null;
+ }
+
+ return false;
}
}
diff --git a/pkg/analyzer/lib/src/workspace/workspace.dart b/pkg/analyzer/lib/src/workspace/workspace.dart
index 5b64e10..f5f037f 100644
--- a/pkg/analyzer/lib/src/workspace/workspace.dart
+++ b/pkg/analyzer/lib/src/workspace/workspace.dart
@@ -2,6 +2,7 @@
// 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/features.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
@@ -38,6 +39,11 @@
/// understand whether arbitrary file paths represent libraries declared within
/// a given package in a Workspace.
abstract class WorkspacePackage {
+ /// Return the [FeatureSet] for all files in the package.
+ ///
+ /// Return `null` if this package does not have a feature set override.
+ FeatureSet get featureSet => null;
+
String get root;
Workspace get workspace;
diff --git a/pkg/analyzer/pubspec.yaml b/pkg/analyzer/pubspec.yaml
index 44445f6..becd0e8 100644
--- a/pkg/analyzer/pubspec.yaml
+++ b/pkg/analyzer/pubspec.yaml
@@ -10,7 +10,7 @@
_fe_analyzer_shared: ^6.0.0
args: ^1.0.0
charcode: ^1.1.0
- cli_util: ^0.1.4
+ cli_util: '>=0.1.4 <0.3.0'
collection: ^1.10.1
convert: ^2.0.0
crypto: ^2.0.0
diff --git a/pkg/analyzer/test/error/error_reporter_test.dart b/pkg/analyzer/test/error/error_reporter_test.dart
index 9eaa852..4abbae8 100644
--- a/pkg/analyzer/test/error/error_reporter_test.dart
+++ b/pkg/analyzer/test/error/error_reporter_test.dart
@@ -10,7 +10,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../generated/test_support.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -19,7 +19,7 @@
}
@reflectiveTest
-class ErrorReporterTest extends DriverResolutionTest {
+class ErrorReporterTest extends PubPackageResolutionTest {
var listener = GatheringErrorListener();
test_creation() async {
@@ -73,8 +73,8 @@
}
test_reportErrorForNode_types_differentNames() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/b.dart', content: 'class B {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/b.dart', content: 'class B {}');
await resolveTestCode(r'''
import 'package:test/a.dart';
import 'package:test/b.dart';
@@ -112,8 +112,8 @@
}
test_reportErrorForNode_types_sameName() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/b.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/b.dart', content: 'class A {}');
await resolveTestCode(r'''
import 'package:test/a.dart';
import 'package:test/b.dart';
@@ -150,8 +150,8 @@
}
test_reportErrorForNode_types_sameName_functionType() async {
- newFile('/test/lib/a.dart', content: 'class A{}');
- newFile('/test/lib/b.dart', content: 'class A{}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A{}');
+ newFile('$testPackageLibPath/b.dart', content: 'class A{}');
await resolveTestCode(r'''
import 'a.dart' as a;
import 'b.dart' as b;
@@ -184,8 +184,8 @@
}
test_reportErrorForNode_types_sameName_nested() async {
- newFile('/test/lib/a.dart', content: 'class A{}');
- newFile('/test/lib/b.dart', content: 'class A{}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A{}');
+ newFile('$testPackageLibPath/b.dart', content: 'class A{}');
await resolveTestCode(r'''
import 'a.dart' as a;
import 'b.dart' as b;
diff --git a/pkg/analyzer/test/generated/constant_test.dart b/pkg/analyzer/test/generated/constant_test.dart
index ddf6aab..097479c 100644
--- a/pkg/analyzer/test/generated/constant_test.dart
+++ b/pkg/analyzer/test/generated/constant_test.dart
@@ -9,7 +9,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -18,7 +18,7 @@
}
@reflectiveTest
-class ConstantEvaluatorTest extends DriverResolutionTest {
+class ConstantEvaluatorTest extends PubPackageResolutionTest {
test_bitAnd_int_int() async {
await _assertValueInt(74 & 42, "74 & 42");
}
diff --git a/pkg/analyzer/test/generated/element_resolver_test.dart b/pkg/analyzer/test/generated/element_resolver_test.dart
index 52d7501..a88deb2 100644
--- a/pkg/analyzer/test/generated/element_resolver_test.dart
+++ b/pkg/analyzer/test/generated/element_resolver_test.dart
@@ -26,7 +26,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import '../util/element_type_matchers.dart';
import 'elements_types_mixin.dart';
import 'test_analysis_context.dart';
@@ -49,9 +49,9 @@
}
@reflectiveTest
-class AnnotationElementResolverTest extends DriverResolutionTest {
+class AnnotationElementResolverTest extends PubPackageResolutionTest {
test_class_namedConstructor() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A.named();
}
@@ -80,7 +80,7 @@
}
test_class_prefixed_namedConstructor() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A.named();
}
@@ -111,7 +111,7 @@
}
test_class_prefixed_staticConstField() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static const V = 0;
}
@@ -141,7 +141,7 @@
}
test_class_prefixed_unnamedConstructor() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A();
}
@@ -169,7 +169,7 @@
}
test_class_staticConstField() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static const V = 0;
}
@@ -197,7 +197,7 @@
}
test_class_unnamedConstructor() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A();
}
@@ -223,7 +223,7 @@
}
test_topLevelVariable() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const V = 0;
''');
await _validateAnnotation('', '@V', (SimpleIdentifier name1,
@@ -247,7 +247,7 @@
}
test_topLevelVariable_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const V = 0;
''');
await _validateAnnotation('as p', '@p.V', (SimpleIdentifier name1,
diff --git a/pkg/analyzer/test/generated/error_suppression_test.dart b/pkg/analyzer/test/generated/error_suppression_test.dart
index 2335951..7c6e3d9 100644
--- a/pkg/analyzer/test/generated/error_suppression_test.dart
+++ b/pkg/analyzer/test/generated/error_suppression_test.dart
@@ -3,10 +3,9 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/src/error/codes.dart';
-import 'package:analyzer/src/test_utilities/package_mixin.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -15,7 +14,7 @@
}
@reflectiveTest
-class ErrorSuppressionTest extends DriverResolutionTest with PackageMixin {
+class ErrorSuppressionTest extends PubPackageResolutionTest {
String get ignoredCode => 'unused_element';
test_does_not_ignore_errors() async {
@@ -116,7 +115,7 @@
}
test_ignore_uniqueName() async {
- addMetaPackage();
+ writeTestPackageConfigWithMeta();
await assertNoErrorsInCode('''
import 'package:meta/meta.dart';
@@ -245,7 +244,7 @@
test_undefined_function_within_flutter_can_be_ignored() async {
await assertErrorsInFile(
- '/workspace/flutterlib/flutter.dart',
+ '$workspaceRootPath/flutterlib/flutter.dart',
'''
// ignore: undefined_function
f() => g();
@@ -256,7 +255,7 @@
test_undefined_function_within_flutter_without_ignore() async {
await assertErrorsInFile(
- '/workspace/flutterlib/flutter.dart',
+ '$workspaceRootPath/flutterlib/flutter.dart',
'''
f() => g();
''',
@@ -266,7 +265,7 @@
test_undefined_prefixed_name_within_flutter_can_be_ignored() async {
await assertErrorsInFile(
- '/workspace/flutterlib/flutter.dart',
+ '$workspaceRootPath/flutterlib/flutter.dart',
'''
import 'dart:collection' as c;
// ignore: undefined_prefixed_name
diff --git a/pkg/analyzer/test/generated/invalid_code_test.dart b/pkg/analyzer/test/generated/invalid_code_test.dart
index 7b2fb4a..dc3b656 100644
--- a/pkg/analyzer/test/generated/invalid_code_test.dart
+++ b/pkg/analyzer/test/generated/invalid_code_test.dart
@@ -7,8 +7,7 @@
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
-import '../src/dart/resolution/with_null_safety_mixin.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -22,7 +21,7 @@
/// errors generated, but we want to make sure that there is at least one,
/// and analysis finishes without exceptions.
@reflectiveTest
-class InvalidCodeTest extends DriverResolutionTest {
+class InvalidCodeTest extends PubPackageResolutionTest {
/// This code results in a method with the empty name, and the default
/// constructor, which also has the empty name. The `Map` in `f` initializer
/// references the empty name.
@@ -347,7 +346,7 @@
}
@reflectiveTest
-class InvalidCodeWithNullSafetyTest extends DriverResolutionTest
+class InvalidCodeWithNullSafetyTest extends PubPackageResolutionTest
with WithNullSafetyMixin {
test_issue_40837() async {
await _assertCanBeAnalyzed('''
diff --git a/pkg/analyzer/test/generated/issues_test.dart b/pkg/analyzer/test/generated/issues_test.dart
index 7c6fdbf9..85286a5 100644
--- a/pkg/analyzer/test/generated/issues_test.dart
+++ b/pkg/analyzer/test/generated/issues_test.dart
@@ -4,7 +4,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -15,7 +15,7 @@
/// Tests for various end-to-end cases reported as user issues, where it is
/// not obvious where to put the test otherwise.
@reflectiveTest
-class IssuesTest extends DriverResolutionTest {
+class IssuesTest extends PubPackageResolutionTest {
/// https://github.com/dart-lang/sdk/issues/38565
///
/// The issue was that type inference for annotation instantiation
diff --git a/pkg/analyzer/test/generated/non_error_resolver_test.dart b/pkg/analyzer/test/generated/non_error_resolver_test.dart
index 286187a..ac6d07b 100644
--- a/pkg/analyzer/test/generated/non_error_resolver_test.dart
+++ b/pkg/analyzer/test/generated/non_error_resolver_test.dart
@@ -4,16 +4,14 @@
import 'dart:async';
-import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/error/codes.dart';
-import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -23,13 +21,7 @@
}
@reflectiveTest
-class NonConstantValueInInitializer extends DriverResolutionTest {
- @override
- AnalysisOptionsImpl get analysisOptions => AnalysisOptionsImpl()
- ..contextFeatures = FeatureSet.forTesting(
- sdkVersion: '2.3.0',
- additionalFeatures: [Feature.constant_update_2018]);
-
+class NonConstantValueInInitializer extends PubPackageResolutionTest {
test_intLiteralInDoubleContext_const_exact() async {
await assertNoErrorsInCode(r'''
const double x = 0;
@@ -63,13 +55,13 @@
}
@reflectiveTest
-class NonErrorResolverTest extends DriverResolutionTest {
+class NonErrorResolverTest extends PubPackageResolutionTest {
test_ambiguousExport() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
class M {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library lib2;
class N {}
''');
@@ -81,12 +73,12 @@
}
test_ambiguousExport_combinators_hide() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library L1;
class A {}
class B {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library L2;
class B {}
class C {}
@@ -99,12 +91,12 @@
}
test_ambiguousExport_combinators_show() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library L1;
class A {}
class B {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library L2;
class B {}
class C {}
@@ -117,7 +109,7 @@
}
test_ambiguousExport_sameDeclaration() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
class N {}
''');
@@ -129,7 +121,7 @@
}
test_ambiguousImport_dart_implicitHide() async {
- newFile('/test/lib/lib.dart', content: r'''
+ newFile('$testPackageLibPath/lib.dart', content: r'''
class Future {
static const zero = 0;
}
@@ -144,17 +136,17 @@
}
test_ambiguousImport_hideCombinator() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
class N {}
class N1 {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library lib2;
class N {}
class N2 {}
''');
- newFile("/test/lib/lib3.dart", content: r'''
+ newFile("$testPackageLibPath/lib3.dart", content: r'''
library lib3;
class N {}
class N3 {}
@@ -172,12 +164,12 @@
}
test_ambiguousImport_showCombinator() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
class N {}
class N1 {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library lib2;
class N {}
class N2 {}
@@ -195,7 +187,7 @@
}
test_annotated_partOfDeclaration() async {
- newFile('/test/lib/part.dart', content: '''
+ newFile('$testPackageLibPath/part.dart', content: '''
@deprecated part of L;
''');
await assertNoErrorsInCode('''
@@ -421,7 +413,7 @@
}
test_assignmentToFinals_importWithPrefix() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
bool x = false;''');
await assertNoErrorsInCode(r'''
@@ -716,7 +708,7 @@
}
test_closure_in_type_inferred_variable_in_other_lib() async {
- newFile('/test/lib/other.dart', content: '''
+ newFile('$testPackageLibPath/other.dart', content: '''
var y = (Object x) => x is int && x.isEven;
''');
await assertNoErrorsInCode('''
@@ -778,13 +770,13 @@
}
test_const_imported_defaultParameterValue_withImportPrefix() async {
- newFile('/test/lib/b.dart', content: r'''
+ newFile('$testPackageLibPath/b.dart', content: r'''
import 'c.dart' as ccc;
class B {
const B([p = ccc.value]);
}
''');
- newFile('/test/lib/c.dart', content: r'''
+ newFile('$testPackageLibPath/c.dart', content: r'''
const int value = 12345;
''');
await assertNoErrorsInCode(r'''
@@ -861,7 +853,7 @@
}
test_constDeferredClass_new() async {
- newFile('/test/lib/lib.dart', content: r'''
+ newFile('$testPackageLibPath/lib.dart', content: r'''
class A {
const A.b();
}
@@ -882,7 +874,7 @@
}
test_constEval_propertyExtraction_fieldStatic_targetType() async {
- newFile("/test/lib/math.dart", content: r'''
+ newFile("$testPackageLibPath/math.dart", content: r'''
library math;
const PI = 3.14;
''');
@@ -903,7 +895,7 @@
}
test_constEval_symbol() async {
- newFile("/test/lib/math.dart", content: r'''
+ newFile("$testPackageLibPath/math.dart", content: r'''
library math;
const PI = 3.14;
''');
@@ -1086,7 +1078,7 @@
}
test_deprecatedMemberUse_hide() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
class A {}
@deprecated
@@ -1532,7 +1524,7 @@
}
test_importDuplicatedLibraryName() async {
- newFile("/test/lib/lib.dart", content: "library lib;");
+ newFile("$testPackageLibPath/lib.dart", content: "library lib;");
await assertErrorsInCode(r'''
library test;
import 'lib.dart';
@@ -1545,8 +1537,8 @@
}
test_importDuplicatedLibraryUnnamed() async {
- newFile("/test/lib/lib1.dart");
- newFile("/test/lib/lib2.dart");
+ newFile("$testPackageLibPath/lib1.dart");
+ newFile("$testPackageLibPath/lib2.dart");
// No warning on duplicate import (https://github.com/dart-lang/sdk/issues/24156)
await assertErrorsInCode(r'''
library test;
@@ -1559,7 +1551,7 @@
}
test_importOfNonLibrary_libraryDeclared() async {
- newFile("/test/lib/part.dart", content: r'''
+ newFile("$testPackageLibPath/part.dart", content: r'''
library lib1;
class A {}
''');
@@ -1571,7 +1563,7 @@
}
test_importOfNonLibrary_libraryNotDeclared() async {
- newFile("/test/lib/part.dart", content: '''
+ newFile("$testPackageLibPath/part.dart", content: '''
class A {}
''');
await assertNoErrorsInCode(r'''
@@ -1582,11 +1574,11 @@
}
test_importPrefixes_withFirstLetterDifference() async {
- newFile("/test/lib/lib1.dart", content: r'''
+ newFile("$testPackageLibPath/lib1.dart", content: r'''
library lib1;
test1() {}
''');
- newFile("/test/lib/lib2.dart", content: r'''
+ newFile("$testPackageLibPath/lib2.dart", content: r'''
library lib2;
test2() {}
''');
@@ -1795,7 +1787,7 @@
}
test_instanceMethodNameCollidesWithSuperclassStatic_field() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library L;
class A {
static var _m;
@@ -1812,7 +1804,7 @@
}
test_instanceMethodNameCollidesWithSuperclassStatic_method() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library L;
class A {
static _m() {}
@@ -1906,7 +1898,7 @@
}
test_invalidAnnotation_constantVariable_field_importWithPrefix() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
class A {
static const C = 0;
@@ -1930,7 +1922,7 @@
}
test_invalidAnnotation_constantVariable_topLevel_importWithPrefix() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
const C = 0;
''');
@@ -1943,7 +1935,7 @@
}
test_invalidAnnotation_constConstructor_importWithPrefix() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
class A {
const A(int p);
@@ -1958,7 +1950,7 @@
}
test_invalidAnnotation_constConstructor_named_importWithPrefix() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
class A {
const A.named(int p);
@@ -2135,12 +2127,12 @@
}
Future test_issue32114() async {
- newFile('/test/lib/a.dart', content: '''
+ newFile('$testPackageLibPath/a.dart', content: '''
class O {}
typedef T Func<T extends O>(T e);
''');
- newFile('/test/lib/b.dart', content: '''
+ newFile('$testPackageLibPath/b.dart', content: '''
import 'a.dart';
export 'a.dart' show Func;
@@ -2190,7 +2182,7 @@
}
test_issue_35320_lists() async {
- newFile('/test/lib/lib.dart', content: '''
+ newFile('$testPackageLibPath/lib.dart', content: '''
const x = const <String>['a'];
''');
await assertNoErrorsInCode('''
@@ -2210,7 +2202,7 @@
}
test_issue_35320_maps() async {
- newFile('/test/lib/lib.dart', content: '''
+ newFile('$testPackageLibPath/lib.dart', content: '''
const x = const <String, String>{'a': 'b'};
''');
await assertNoErrorsInCode('''
@@ -2230,7 +2222,7 @@
}
test_loadLibraryDefined() async {
- newFile('/test/lib/lib.dart', content: r'''
+ newFile('$testPackageLibPath/lib.dart', content: r'''
library lib;
foo() => 22;''');
await assertNoErrorsInCode(r'''
@@ -2802,13 +2794,13 @@
}
test_optionalNew_rewrite() async {
- newFile("/test/lib/a.dart", content: r'''
+ newFile("$testPackageLibPath/a.dart", content: r'''
class A {
const A();
const A.named();
}
''');
- newFile("/test/lib/b.dart", content: r'''
+ newFile("$testPackageLibPath/b.dart", content: r'''
import 'a.dart';
import 'a.dart' as p;
@@ -2838,7 +2830,7 @@
}
test_optionalNew_rewrite_instantiatesToBounds() async {
- newFile("/test/lib/a.dart", content: r'''
+ newFile("$testPackageLibPath/a.dart", content: r'''
class Unbounded<T> {
const Unbounded();
const Unbounded.named();
@@ -2848,7 +2840,7 @@
const Bounded.named();
}
''');
- newFile("/test/lib/b.dart", content: r'''
+ newFile("$testPackageLibPath/b.dart", content: r'''
import 'a.dart';
import 'a.dart' as p;
@@ -3043,13 +3035,13 @@
}
test_sharedDeferredPrefix() async {
- newFile('/test/lib/lib1.dart', content: r'''
+ newFile('$testPackageLibPath/lib1.dart', content: r'''
f1() {}
''');
- newFile('/test/lib/lib2.dart', content: r'''
+ newFile('$testPackageLibPath/lib2.dart', content: r'''
f2() {}
''');
- newFile('/test/lib/lib3.dart', content: r'''
+ newFile('$testPackageLibPath/lib3.dart', content: r'''
f3() {}
''');
await assertNoErrorsInCode(r'''
@@ -3067,7 +3059,7 @@
}
test_typedef_not_function() async {
- newFile('/test/lib/a.dart', content: '''
+ newFile('$testPackageLibPath/a.dart', content: '''
typedef F = int;
''');
await assertNoErrorsInCode('''
@@ -3331,7 +3323,7 @@
}
test_typeType_class_prefixed() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
class C {}''');
await assertNoErrorsInCode(r'''
@@ -3354,7 +3346,7 @@
}
test_typeType_functionTypeAlias_prefixed() async {
- newFile("/test/lib/lib.dart", content: r'''
+ newFile("$testPackageLibPath/lib.dart", content: r'''
library lib;
typedef F();''');
await assertNoErrorsInCode(r'''
diff --git a/pkg/analyzer/test/generated/non_hint_code_test.dart b/pkg/analyzer/test/generated/non_hint_code_test.dart
index 29959b1..bd32129 100644
--- a/pkg/analyzer/test/generated/non_hint_code_test.dart
+++ b/pkg/analyzer/test/generated/non_hint_code_test.dart
@@ -5,7 +5,7 @@
import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import 'test_support.dart';
main() {
@@ -15,7 +15,7 @@
}
@reflectiveTest
-class NonHintCodeTest extends DriverResolutionTest {
+class NonHintCodeTest extends PubPackageResolutionTest {
test_issue20904BuggyTypePromotionAtIfJoin_1() async {
// https://code.google.com/p/dart/issues/detail?id=20904
await assertErrorsInCode(r'''
@@ -204,7 +204,7 @@
}
}
-class PubSuggestionCodeTest extends DriverResolutionTest {
+class PubSuggestionCodeTest extends PubPackageResolutionTest {
// TODO(brianwilkerson) The tests in this class are not being run, and all but
// the first would fail. We should implement these checks and enable the
// tests.
diff --git a/pkg/analyzer/test/generated/parser_fasta_test.dart b/pkg/analyzer/test/generated/parser_fasta_test.dart
index fd9767c..f124938 100644
--- a/pkg/analyzer/test/generated/parser_fasta_test.dart
+++ b/pkg/analyzer/test/generated/parser_fasta_test.dart
@@ -172,6 +172,16 @@
expect(invocation.argumentList.arguments, hasLength(0));
}
+ void test_parseField_abstract() {
+ createParser('abstract int i;', featureSet: nonNullable);
+ ClassMember member = parser.parseClassMember('C');
+ expect(member, isNotNull);
+ assertNoErrors();
+ expect(member, isFieldDeclaration);
+ FieldDeclaration field = member;
+ expect(field.abstractKeyword, isNotNull);
+ }
+
void test_parseField_const_late() {
createParser('const late T f = 0;', featureSet: nonNullable);
ClassMember member = parser.parseClassMember('C');
@@ -321,6 +331,16 @@
expect(variable.name, isNotNull);
}
+ void test_parseField_non_abstract() {
+ createParser('int i;', featureSet: nonNullable);
+ ClassMember member = parser.parseClassMember('C');
+ expect(member, isNotNull);
+ assertNoErrors();
+ expect(member, isFieldDeclaration);
+ FieldDeclaration field = member;
+ expect(field.abstractKeyword, isNull);
+ }
+
void test_parseField_var_late() {
createParser('var late f;', featureSet: nonNullable);
ClassMember member = parser.parseClassMember('C');
diff --git a/pkg/analyzer/test/generated/resolver_test.dart b/pkg/analyzer/test/generated/resolver_test.dart
index bc21731..1e9056d 100644
--- a/pkg/analyzer/test/generated/resolver_test.dart
+++ b/pkg/analyzer/test/generated/resolver_test.dart
@@ -15,7 +15,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import 'resolver_test_case.dart';
main() {
@@ -28,7 +28,7 @@
}
@reflectiveTest
-class ErrorResolverTest extends DriverResolutionTest {
+class ErrorResolverTest extends PubPackageResolutionTest {
test_breakLabelOnSwitchMember() async {
await assertErrorsInCode(r'''
class A {
@@ -107,7 +107,7 @@
}
@reflectiveTest
-class PrefixedNamespaceTest extends DriverResolutionTest {
+class PrefixedNamespaceTest extends PubPackageResolutionTest {
void test_lookup_missing() {
ClassElement element = ElementFactory.classElement2('A');
PrefixedNamespace namespace = PrefixedNamespace('p', _toMap([element]));
@@ -307,7 +307,7 @@
/// The class `StrictModeTest` contains tests to ensure that the correct errors
/// and warnings are reported when the analysis engine is run in strict mode.
@reflectiveTest
-class StrictModeTest extends DriverResolutionTest {
+class StrictModeTest extends PubPackageResolutionTest {
test_assert_is() async {
await assertErrorsInCode(r'''
int f(num n) {
@@ -447,7 +447,7 @@
}
@reflectiveTest
-class TypePropagationTest extends DriverResolutionTest {
+class TypePropagationTest extends PubPackageResolutionTest {
test_assignment_null() async {
String code = r'''
main() {
@@ -496,7 +496,7 @@
}
test_invocation_target_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int max(int x, int y) => 0;
''');
await resolveTestCode('''
@@ -558,7 +558,7 @@
}
test_objectAccessInference_disabled_for_library_prefix() async {
- newFile('/test/lib/a.dart', content: '''
+ newFile('$testPackageLibPath/a.dart', content: '''
dynamic get hashCode => 42;
''');
await assertNoErrorsInCode('''
@@ -579,7 +579,7 @@
}
test_objectMethodInference_disabled_for_library_prefix() async {
- newFile('/test/lib/a.dart', content: '''
+ newFile('$testPackageLibPath/a.dart', content: '''
dynamic toString = (int x) => x + 42;
''');
await assertNoErrorsInCode('''
diff --git a/pkg/analyzer/test/generated/resolver_test_case.dart b/pkg/analyzer/test/generated/resolver_test_case.dart
index 04d739a..dddd438 100644
--- a/pkg/analyzer/test/generated/resolver_test_case.dart
+++ b/pkg/analyzer/test/generated/resolver_test_case.dart
@@ -33,7 +33,7 @@
import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
import 'package:test/test.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import 'test_analysis_context.dart';
import 'test_support.dart';
@@ -638,7 +638,7 @@
}
/// Shared infrastructure for [StaticTypeAnalyzer2Test].
-class StaticTypeAnalyzer2TestShared extends DriverResolutionTest {
+class StaticTypeAnalyzer2TestShared extends PubPackageResolutionTest {
/// Find the expression that starts at the offset of [search] and validate its
/// that its static type matches the given [type].
///
diff --git a/pkg/analyzer/test/generated/simple_resolver_test.dart b/pkg/analyzer/test/generated/simple_resolver_test.dart
index 09bb730..d6ce37b 100644
--- a/pkg/analyzer/test/generated/simple_resolver_test.dart
+++ b/pkg/analyzer/test/generated/simple_resolver_test.dart
@@ -8,7 +8,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import 'resolver_test_case.dart';
main() {
@@ -18,7 +18,7 @@
}
@reflectiveTest
-class SimpleResolverTest extends DriverResolutionTest {
+class SimpleResolverTest extends PubPackageResolutionTest {
test_argumentResolution_required_matching() async {
await resolveTestCode(r'''
class A {
@@ -422,7 +422,7 @@
}
test_entryPoint_exported() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
main() {}
''');
@@ -457,7 +457,7 @@
}
test_enum_externalLibrary() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
enum EEE {A, B, C}
''');
await assertNoErrorsInCode(r'''
@@ -667,11 +667,11 @@
}
test_import_hide() async {
- newFile('/test/lib/lib1.dart', content: r'''
+ newFile('$testPackageLibPath/lib1.dart', content: r'''
set foo(value) {}
class A {}''');
- newFile('/test/lib/lib2.dart', content: r'''
+ newFile('$testPackageLibPath/lib2.dart', content: r'''
set foo(value) {}''');
await assertNoErrorsInCode(r'''
@@ -686,7 +686,7 @@
}
test_import_prefix() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
f(int x) {
return x * x;
}''');
@@ -755,7 +755,7 @@
}
test_import_spaceInUri() async {
- newFile('/test/lib/sub folder/a.dart', content: r'''
+ newFile('$testPackageLibPath/sub folder/a.dart', content: r'''
foo() {}''');
await assertNoErrorsInCode(r'''
diff --git a/pkg/analyzer/test/generated/static_type_warning_code_test.dart b/pkg/analyzer/test/generated/static_type_warning_code_test.dart
index 14674c4..0256b50 100644
--- a/pkg/analyzer/test/generated/static_type_warning_code_test.dart
+++ b/pkg/analyzer/test/generated/static_type_warning_code_test.dart
@@ -5,7 +5,7 @@
import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -15,7 +15,7 @@
}
@reflectiveTest
-class StaticTypeWarningCodeTest extends DriverResolutionTest {
+class StaticTypeWarningCodeTest extends PubPackageResolutionTest {
test_assert_message_suppresses_type_promotion() async {
// If a variable is assigned to inside the expression for an assert
// message, type promotion should be suppressed, just as it would be if the
@@ -597,7 +597,7 @@
}
@reflectiveTest
-class StrongModeStaticTypeWarningCodeTest extends DriverResolutionTest {
+class StrongModeStaticTypeWarningCodeTest extends PubPackageResolutionTest {
test_legalAsyncGeneratorReturnType_function_supertypeOfStream() async {
await assertNoErrorsInCode('''
import 'dart:async';
diff --git a/pkg/analyzer/test/generated/static_warning_code_test.dart b/pkg/analyzer/test/generated/static_warning_code_test.dart
index beea4a3..de9b311 100644
--- a/pkg/analyzer/test/generated/static_warning_code_test.dart
+++ b/pkg/analyzer/test/generated/static_warning_code_test.dart
@@ -5,7 +5,7 @@
import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -14,7 +14,7 @@
}
@reflectiveTest
-class StaticWarningCodeTest extends DriverResolutionTest {
+class StaticWarningCodeTest extends PubPackageResolutionTest {
// TODO(brianwilkerson) Figure out what to do with the rest of these tests.
// The names do not correspond to diagnostic codes, so it isn't clear what
// they're testing.
diff --git a/pkg/analyzer/test/generated/strong_mode_test.dart b/pkg/analyzer/test/generated/strong_mode_test.dart
index efa2a44..4d01e88 100644
--- a/pkg/analyzer/test/generated/strong_mode_test.dart
+++ b/pkg/analyzer/test/generated/strong_mode_test.dart
@@ -16,7 +16,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../src/dart/resolution/driver_resolution.dart';
+import '../src/dart/resolution/context_collection_resolution.dart';
import '../utils.dart';
import 'resolver_test_case.dart';
import 'test_support.dart';
@@ -3773,7 +3773,7 @@
}
@reflectiveTest
-class StrongModeTypePropagationTest extends DriverResolutionTest {
+class StrongModeTypePropagationTest extends PubPackageResolutionTest {
test_foreachInference_dynamic_disabled() async {
await resolveTestCode(r'''
main() {
diff --git a/pkg/analyzer/test/src/clients/angular_analyzer_plugin/resolve_template_node_test.dart b/pkg/analyzer/test/src/clients/angular_analyzer_plugin/resolve_template_node_test.dart
index 0af2907..810e4e7 100644
--- a/pkg/analyzer/test/src/clients/angular_analyzer_plugin/resolve_template_node_test.dart
+++ b/pkg/analyzer/test/src/clients/angular_analyzer_plugin/resolve_template_node_test.dart
@@ -11,7 +11,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../dart/resolution/driver_resolution.dart';
+import '../../dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -20,7 +20,7 @@
}
@reflectiveTest
-class ResolveTemplateNodeTest extends DriverResolutionTest {
+class ResolveTemplateNodeTest extends PubPackageResolutionTest {
test_asExpression() async {
await assertNoErrorsInCode(r'''
class MyComponent {}
diff --git a/pkg/analyzer/test/src/context/builder_test.dart b/pkg/analyzer/test/src/context/builder_test.dart
index 14729ad..214bf41 100644
--- a/pkg/analyzer/test/src/context/builder_test.dart
+++ b/pkg/analyzer/test/src/context/builder_test.dart
@@ -402,7 +402,7 @@
void test_createWorkspace_hasPackagesFile_hasDartToolAndPubspec() {
newFile('/workspace/.packages');
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
Workspace workspace = ContextBuilder.createWorkspace(resourceProvider,
convertPath('/workspace/project/lib/lib.dart'), builder);
expect(workspace, TypeMatcher<PackageBuildWorkspace>());
@@ -410,7 +410,7 @@
void test_createWorkspace_hasPackagesFile_hasPubspec() {
newFile('/workspace/.packages');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
Workspace workspace = ContextBuilder.createWorkspace(resourceProvider,
convertPath('/workspace/project/lib/lib.dart'), builder);
expect(workspace, TypeMatcher<PubWorkspace>());
@@ -433,7 +433,7 @@
void test_createWorkspace_noPackagesFile_hasDartToolAndPubspec() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
Workspace workspace = ContextBuilder.createWorkspace(resourceProvider,
convertPath('/workspace/project/lib/lib.dart'), builder);
expect(workspace, TypeMatcher<PackageBuildWorkspace>());
@@ -449,7 +449,7 @@
}
void test_createWorkspace_noPackagesFile_hasPubspec() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
Workspace workspace = ContextBuilder.createWorkspace(resourceProvider,
convertPath('/workspace/project/lib/lib.dart'), builder);
expect(workspace, TypeMatcher<PubWorkspace>());
@@ -552,7 +552,7 @@
newFile(filePath, content: '''
linter:
rules:
- - empty_constructor_bodies
+ - non_existent_lint_rule
''');
AnalysisOptions options = builder.getAnalysisOptions(path);
@@ -648,7 +648,7 @@
newFile(filePath, content: '''
linter:
rules:
- - empty_constructor_bodies
+ - non_existent_lint_rule
''');
AnalysisOptions options = builder.getAnalysisOptions(path);
diff --git a/pkg/analyzer/test/src/dart/analysis/dependency/base.dart b/pkg/analyzer/test/src/dart/analysis/dependency/base.dart
index b217244..6c12cef 100644
--- a/pkg/analyzer/test/src/dart/analysis/dependency/base.dart
+++ b/pkg/analyzer/test/src/dart/analysis/dependency/base.dart
@@ -8,9 +8,9 @@
import 'package:meta/meta.dart';
import 'package:test/test.dart';
-import '../../resolution/driver_resolution.dart';
+import '../../resolution/context_collection_resolution.dart';
-class BaseDependencyTest extends DriverResolutionTest {
+class BaseDependencyTest extends PubPackageResolutionTest {
// DependencyTracker tracker;
String a;
String b;
@@ -62,7 +62,7 @@
// }
newFile(path, content: content);
- driver.changeFile(path);
+ driverFor(path).changeFile(path);
var units = await _resolveLibrary(path);
var uri = units.first.declaredElement.source.uri;
@@ -104,9 +104,9 @@
super.setUp();
// var logger = PerformanceLog(null);
// tracker = DependencyTracker(logger);
- a = convertPath('/test/lib/a.dart');
- b = convertPath('/test/lib/b.dart');
- c = convertPath('/test/lib/c.dart');
+ a = convertPath('$testPackageLibPath/a.dart');
+ b = convertPath('$testPackageLibPath/b.dart');
+ c = convertPath('$testPackageLibPath/c.dart');
aUri = Uri.parse('package:test/a.dart');
bUri = Uri.parse('package:test/b.dart');
cUri = Uri.parse('package:test/c.dart');
@@ -138,7 +138,8 @@
}
Future<List<CompilationUnit>> _resolveLibrary(String libraryPath) async {
- var resolvedLibrary = await driver.getResolvedLibrary(libraryPath);
+ var session = contextFor(libraryPath).currentSession;
+ var resolvedLibrary = await session.getResolvedLibrary(libraryPath);
return resolvedLibrary.units.map((ru) => ru.unit).toList();
}
}
diff --git a/pkg/analyzer/test/src/dart/analysis/driver_resolution_test.dart b/pkg/analyzer/test/src/dart/analysis/driver_resolution_test.dart
index 90c11509..e6cd991 100644
--- a/pkg/analyzer/test/src/dart/analysis/driver_resolution_test.dart
+++ b/pkg/analyzer/test/src/dart/analysis/driver_resolution_test.dart
@@ -20,7 +20,7 @@
import '../../../generated/elements_types_mixin.dart';
import '../../../utils.dart';
-import '../resolution/driver_resolution.dart';
+import '../resolution/context_collection_resolution.dart';
import 'base.dart';
main() {
@@ -38,7 +38,7 @@
/// Integration tests for resolution.
@reflectiveTest
-class AnalysisDriverResolutionTest extends DriverResolutionTest
+class AnalysisDriverResolutionTest extends PubPackageResolutionTest
with ElementsTypesMixin {
void assertDeclaredVariableType(SimpleIdentifier node, String expected) {
VariableElement element = node.staticElement;
@@ -250,7 +250,7 @@
}
test_annotation_onDirective_part() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
part of 'test.dart';
''');
addTestFile(r'''
@@ -273,7 +273,7 @@
}
test_annotation_onDirective_partOf() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
part 'test.dart';
''');
addTestFile(r'''
@@ -394,7 +394,7 @@
}
test_annotation_prefixed_classField() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static const a = 1;
}
@@ -433,7 +433,7 @@
}
test_annotation_prefixed_constructor() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A(int a, {int b});
}
@@ -474,7 +474,7 @@
}
test_annotation_prefixed_constructor_named() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
const A.named(int a, {int b});
}
@@ -517,7 +517,7 @@
}
test_annotation_prefixed_topLevelVariable() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const topAnnotation = 1;
''');
addTestFile(r'''
@@ -1395,7 +1395,7 @@
}
test_deferredImport_loadLibrary_invocation() async {
- newFile('/test/lib/a.dart');
+ newFile('$testPackageLibPath/a.dart');
addTestFile(r'''
import 'a.dart' deferred as a;
main() {
@@ -1419,7 +1419,7 @@
}
test_deferredImport_loadLibrary_invocation_argument() async {
- newFile('/test/lib/a.dart');
+ newFile('$testPackageLibPath/a.dart');
addTestFile(r'''
import 'a.dart' deferred as a;
var b = 1;
@@ -1453,7 +1453,7 @@
}
test_deferredImport_loadLibrary_tearOff() async {
- newFile('/test/lib/a.dart');
+ newFile('$testPackageLibPath/a.dart');
addTestFile(r'''
import 'a.dart' deferred as a;
main() {
@@ -1476,7 +1476,7 @@
}
test_deferredImport_variable() async {
- newFile('/test/lib/a.dart', content: 'var v = 0;');
+ newFile('$testPackageLibPath/a.dart', content: 'var v = 0;');
addTestFile(r'''
import 'a.dart' deferred as a;
main() async {
@@ -1516,7 +1516,7 @@
}
test_directive_export() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class MyClass {}
int myVar;
int get myGetter => 0;
@@ -1564,7 +1564,7 @@
}
test_directive_import_hide() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class MyClass {}
int myVar;
int get myGetter => 0;
@@ -1612,7 +1612,7 @@
}
test_directive_import_show() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class MyClass {}
int myVar;
int get myGetter => 0;
@@ -2172,7 +2172,7 @@
}
test_instanceCreation_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class C<T> {
C(T p);
C.named(T p);
@@ -3580,7 +3580,7 @@
@failingTest
test_invalid_nonTypeAsType_topLevelFunction_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int T() => 0;
''');
addTestFile(r'''
@@ -3648,7 +3648,7 @@
@failingTest
test_invalid_nonTypeAsType_topLevelVariable_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int T;
''');
addTestFile(r'''
@@ -5630,7 +5630,7 @@
}
test_optionalConst_prefixed() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class C {
const C();
const C.named();
@@ -6154,7 +6154,7 @@
}
test_prefixedIdentifier_importPrefix_className() async {
- newFile('/test/lib/lib.dart', content: '''
+ newFile('$testPackageLibPath/lib.dart', content: '''
class MyClass {}
typedef void MyFunctionTypeAlias();
int myTopVariable;
@@ -7751,9 +7751,9 @@
}
test_typeAnnotation_prefixed() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/b.dart', content: "export 'a.dart';");
- newFile('/test/lib/c.dart', content: "export 'a.dart';");
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/b.dart', content: "export 'a.dart';");
+ newFile('$testPackageLibPath/c.dart', content: "export 'a.dart';");
addTestFile(r'''
import 'b.dart' as b;
import 'c.dart' as c;
diff --git a/pkg/analyzer/test/src/dart/analysis/results/get_element_declaration_test.dart b/pkg/analyzer/test/src/dart/analysis/results/get_element_declaration_test.dart
index 7edf053..69e058e 100644
--- a/pkg/analyzer/test/src/dart/analysis/results/get_element_declaration_test.dart
+++ b/pkg/analyzer/test/src/dart/analysis/results/get_element_declaration_test.dart
@@ -9,7 +9,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../resolution/driver_resolution.dart';
+import '../../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -18,7 +18,7 @@
});
}
-mixin GetElementDeclarationMixin implements DriverResolutionTest {
+mixin GetElementDeclarationMixin implements PubPackageResolutionTest {
Future<ElementDeclarationResult> getElementDeclaration(Element element);
test_class() async {
@@ -60,7 +60,7 @@
}
test_class_inPart() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
part of 'test.dart';
class A {}
''');
@@ -403,7 +403,7 @@
}
@reflectiveTest
-class GetElementDeclarationParsedTest extends DriverResolutionTest
+class GetElementDeclarationParsedTest extends PubPackageResolutionTest
with GetElementDeclarationMixin {
@override
Future<ElementDeclarationResult> getElementDeclaration(
@@ -414,12 +414,13 @@
}
ParsedLibraryResultImpl _getParsedLibrary(String path) {
- return driver.getParsedLibrary(path);
+ var session = contextFor(path).currentSession;
+ return session.getParsedLibrary(path);
}
}
@reflectiveTest
-class GetElementDeclarationResolvedTest extends DriverResolutionTest
+class GetElementDeclarationResolvedTest extends PubPackageResolutionTest
with GetElementDeclarationMixin {
@override
Future<ElementDeclarationResult> getElementDeclaration(
@@ -430,6 +431,7 @@
}
Future<ResolvedLibraryResult> _getResolvedLibrary(String path) {
- return driver.getResolvedLibrary(path);
+ var session = contextFor(path).currentSession;
+ return session.getResolvedLibrary(path);
}
}
diff --git a/pkg/analyzer/test/src/dart/analysis/session_helper_test.dart b/pkg/analyzer/test/src/dart/analysis/session_helper_test.dart
index 1a390a1..c9d188a 100644
--- a/pkg/analyzer/test/src/dart/analysis/session_helper_test.dart
+++ b/pkg/analyzer/test/src/dart/analysis/session_helper_test.dart
@@ -8,7 +8,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../resolution/driver_resolution.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -17,17 +17,18 @@
}
@reflectiveTest
-class AnalysisSessionHelperTest extends DriverResolutionTest {
+class AnalysisSessionHelperTest extends PubPackageResolutionTest {
AnalysisSessionHelper helper;
@override
void setUp() {
super.setUp();
- helper = AnalysisSessionHelper(driver.currentSession);
+ var session = contextFor(testFilePath).currentSession;
+ helper = AnalysisSessionHelper(session);
}
test_getClass_defined() async {
- var file = newFile('/test/lib/c.dart', content: r'''
+ var file = newFile('$testPackageLibPath/c.dart', content: r'''
class C {}
int v = 0;
''');
@@ -39,7 +40,7 @@
}
test_getClass_defined_notClass() async {
- var file = newFile('/test/lib/c.dart', content: r'''
+ var file = newFile('$testPackageLibPath/c.dart', content: r'''
int v = 0;
''');
String uri = file.toUri().toString();
@@ -49,10 +50,10 @@
}
test_getClass_exported() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
- var bFile = newFile('/test/lib/b.dart', content: r'''
+ var bFile = newFile('$testPackageLibPath/b.dart', content: r'''
export 'a.dart';
''');
String bUri = bFile.toUri().toString();
@@ -63,10 +64,10 @@
}
test_getClass_imported() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
- var bFile = newFile('/test/lib/b.dart', content: r'''
+ var bFile = newFile('$testPackageLibPath/b.dart', content: r'''
import 'a.dart';
''');
String bUri = bFile.toUri().toString();
@@ -96,7 +97,7 @@
}
test_getTopLevelPropertyAccessor_defined_getter() async {
- var file = newFile('/test/lib/test.dart', content: r'''
+ var file = newFile('$testPackageLibPath/test.dart', content: r'''
int get a => 0;
''');
String uri = file.toUri().toString();
@@ -108,7 +109,7 @@
}
test_getTopLevelPropertyAccessor_defined_setter() async {
- var file = newFile('/test/lib/test.dart', content: r'''
+ var file = newFile('$testPackageLibPath/test.dart', content: r'''
set a(_) {}
''');
String uri = file.toUri().toString();
@@ -120,7 +121,7 @@
}
test_getTopLevelPropertyAccessor_defined_variable() async {
- var file = newFile('/test/lib/test.dart', content: r'''
+ var file = newFile('$testPackageLibPath/test.dart', content: r'''
int a;
''');
String uri = file.toUri().toString();
@@ -132,10 +133,10 @@
}
test_getTopLevelPropertyAccessor_exported() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int a;
''');
- var bFile = newFile('/test/lib/b.dart', content: r'''
+ var bFile = newFile('$testPackageLibPath/b.dart', content: r'''
export 'a.dart';
''');
String bUri = bFile.toUri().toString();
@@ -147,10 +148,10 @@
}
test_getTopLevelPropertyAccessor_imported() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int a;
''');
- var bFile = newFile('/test/lib/b.dart', content: r'''
+ var bFile = newFile('$testPackageLibPath/b.dart', content: r'''
import 'a.dart';
''');
String bUri = bFile.toUri().toString();
@@ -160,7 +161,7 @@
}
test_getTopLevelPropertyAccessor_notDefined() async {
- var file = newFile('/test/lib/test.dart', content: r'''
+ var file = newFile('$testPackageLibPath/test.dart', content: r'''
int a;
''');
String uri = file.toUri().toString();
@@ -170,7 +171,7 @@
}
test_getTopLevelPropertyAccessor_notPropertyAccessor() async {
- var file = newFile('/test/lib/test.dart', content: r'''
+ var file = newFile('$testPackageLibPath/test.dart', content: r'''
int a() {}
''');
String uri = file.toUri().toString();
diff --git a/pkg/analyzer/test/src/dart/ast/element_locator_test.dart b/pkg/analyzer/test/src/dart/ast/element_locator_test.dart
index f63cc86..46d0ab5 100644
--- a/pkg/analyzer/test/src/dart/ast/element_locator_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/element_locator_test.dart
@@ -8,7 +8,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../../../util/element_type_matchers.dart';
-import '../resolution/driver_resolution.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -17,7 +17,7 @@
}
@reflectiveTest
-class ElementLocatorTest extends DriverResolutionTest {
+class ElementLocatorTest extends PubPackageResolutionTest {
@override
AnalysisOptionsImpl get analysisOptions {
return AnalysisOptionsImpl()..hint = false;
@@ -199,7 +199,7 @@
}
test_locate_InstanceCreationExpression_type_prefixedIdentifier() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
await resolveTestCode(r'''
@@ -215,7 +215,7 @@
}
test_locate_InstanceCreationExpression_type_simpleIdentifier() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
''');
await resolveTestCode(r'''
class A {}
@@ -275,19 +275,22 @@
expect(element, isFunctionElement);
}
- test_locate_PartOfDirective() async {
- var libPath = convertPath('/test/lib/lib.dart');
- var partPath = convertPath('/test/lib/test.dart');
+ test_locate_PartOfDirective_withName() async {
+ var libPath = convertPath('$testPackageLibPath/lib.dart');
+ var partPath = convertPath('$testPackageLibPath/test.dart');
newFile(libPath, content: r'''
library my.lib;
part 'test.dart';
''');
- driver.addFile(libPath);
- driver.addFile(partPath);
+ newFile(partPath, content: r'''
+part of my.lib;
+''');
- await resolveTestCode('part of my.lib;');
+ await resolveFile(libPath);
+
+ await resolveFile2(partPath);
var node = findNode.partOf('part of');
var element = ElementLocator.locate(node);
expect(element, isLibraryElement);
@@ -318,7 +321,7 @@
}
test_locate_StringLiteral_exportUri() async {
- newFile("/test/lib/foo.dart", content: '');
+ newFile("$testPackageLibPath/foo.dart", content: '');
await resolveTestCode("export 'foo.dart';");
var node = findNode.stringLiteral('foo.dart');
var element = ElementLocator.locate(node);
@@ -333,7 +336,7 @@
}
test_locate_StringLiteral_importUri() async {
- newFile("/test/lib/foo.dart", content: '');
+ newFile("$testPackageLibPath/foo.dart", content: '');
await resolveTestCode("import 'foo.dart';");
var node = findNode.stringLiteral('foo.dart');
var element = ElementLocator.locate(node);
@@ -341,7 +344,7 @@
}
test_locate_StringLiteral_partUri() async {
- newFile("/test/lib/foo.dart", content: 'part of lib;');
+ newFile("$testPackageLibPath/foo.dart", content: 'part of lib;');
await resolveTestCode('''
library lib;
diff --git a/pkg/analyzer/test/src/dart/ast/to_source_visitor_test.dart b/pkg/analyzer/test/src/dart/ast/to_source_visitor_test.dart
index df8306d..f93f0ce 100644
--- a/pkg/analyzer/test/src/dart/ast/to_source_visitor_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/to_source_visitor_test.dart
@@ -898,6 +898,14 @@
[AstTestFactory.identifier3('o')])));
}
+ void test_visitFieldDeclaration_abstract() {
+ _assertSource(
+ "abstract var a;",
+ AstTestFactory.fieldDeclaration(
+ false, Keyword.VAR, null, [AstTestFactory.variableDeclaration("a")],
+ isAbstract: true));
+ }
+
void test_visitFieldDeclaration_instance() {
_assertSource(
"var a;",
diff --git a/pkg/analyzer/test/src/dart/ast/utilities_test.dart b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
index be73747..06798f1 100644
--- a/pkg/analyzer/test/src/dart/ast/utilities_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
@@ -300,6 +300,26 @@
expect(toNode.element, same(element));
}
+ void test_visitFieldDeclaration_abstract() {
+ FieldDeclaration fromNode = AstTestFactory.fieldDeclaration(
+ false, Keyword.VAR, null, [AstTestFactory.variableDeclaration('x')],
+ isAbstract: false);
+ FieldElement element = FieldElementImpl('x', -1);
+ fromNode.fields.variables[0].name.staticElement = element;
+ FieldDeclaration toNode1 = AstTestFactory.fieldDeclaration(
+ false, Keyword.VAR, null, [AstTestFactory.variableDeclaration('x')],
+ isAbstract: false);
+ ResolutionCopier.copyResolutionData(fromNode, toNode1);
+ // Nodes matched so resolution data should have been copied.
+ expect(toNode1.fields.variables[0].declaredElement, same(element));
+ FieldDeclaration toNode2 = AstTestFactory.fieldDeclaration(
+ false, Keyword.VAR, null, [AstTestFactory.variableDeclaration('x')],
+ isAbstract: true);
+ ResolutionCopier.copyResolutionData(fromNode, toNode1);
+ // Nodes didn't match so resolution data should not have been copied.
+ expect(toNode2.fields.variables[0].declaredElement, isNull);
+ }
+
void test_visitForEachPartsWithDeclaration() {
ForEachPartsWithDeclaration createNode() =>
astFactory.forEachPartsWithDeclaration(
diff --git a/pkg/analyzer/test/src/dart/constant/evaluation_test.dart b/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
index 78c6212..6cd1ae9 100644
--- a/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
+++ b/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
@@ -3,7 +3,6 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/analysis/declared_variables.dart';
-import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/error/error.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
@@ -14,8 +13,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../../../generated/test_support.dart';
-import '../resolution/driver_resolution.dart';
-import '../resolution/with_null_safety_mixin.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -301,14 +299,15 @@
}
}
-class ConstantVisitorTestSupport extends DriverResolutionTest {
+class ConstantVisitorTestSupport extends PubPackageResolutionTest {
DartObjectImpl _evaluateConstant(
String name, {
List<ErrorCode> errorCodes,
Map<String, String> declaredVariables = const {},
Map<String, DartObjectImpl> lexicalEnvironment,
}) {
- var options = driver.analysisOptions as AnalysisOptionsImpl;
+ var analysisContext = contextFor(this.result.path);
+ var options = analysisContext.analysisOptions as AnalysisOptionsImpl;
var expression = findNode.topVariableDeclarationByName(name).initializer;
var source = this.result.unit.declaredElement.source;
@@ -344,10 +343,14 @@
class ConstantVisitorWithConstantUpdate2018Test
extends ConstantVisitorTestSupport {
@override
- AnalysisOptionsImpl get analysisOptions => AnalysisOptionsImpl()
- ..contextFeatures = FeatureSet.fromEnableFlags(
- [EnableString.constant_update_2018, EnableString.triple_shift],
+ void setUp() {
+ super.setUp();
+ writeTestPackageAnalysisOptionsFile(
+ AnalysisOptionsFileConfig(
+ experiments: [EnableString.triple_shift],
+ ),
);
+ }
test_visitAsExpression_instanceOfSameClass() async {
await resolveTestCode('''
diff --git a/pkg/analyzer/test/src/dart/constant/potentially_constant_test.dart b/pkg/analyzer/test/src/dart/constant/potentially_constant_test.dart
index 225f997..4ba18ab 100644
--- a/pkg/analyzer/test/src/dart/constant/potentially_constant_test.dart
+++ b/pkg/analyzer/test/src/dart/constant/potentially_constant_test.dart
@@ -7,8 +7,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../resolution/driver_resolution.dart';
-import '../resolution/with_null_safety_mixin.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -20,7 +19,7 @@
}
@reflectiveTest
-class IsConstantTypeExpressionTest extends DriverResolutionTest {
+class IsConstantTypeExpressionTest extends PubPackageResolutionTest {
test_class() async {
await _assertConst(r'''
int x;
@@ -28,7 +27,7 @@
}
test_class_prefix() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
await _assertConst(r'''
@@ -38,7 +37,7 @@
}
test_class_prefix_deferred() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
await _assertNeverConst(r'''
@@ -180,7 +179,7 @@
}
@reflectiveTest
-class PotentiallyConstantTest extends DriverResolutionTest {
+class PotentiallyConstantTest extends PubPackageResolutionTest {
test_adjacentStrings() async {
await _assertConst(r'''
var x = 'a' 'b';
@@ -489,7 +488,7 @@
}
test_prefixedIdentifier_importPrefix_deferred() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const a = 0;
''');
await _assertNotConst(r'''
@@ -499,7 +498,7 @@
}
test_prefixedIdentifier_importPrefix_function() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
void f() {}
''');
await _assertConst(r'''
@@ -509,7 +508,7 @@
}
test_prefixedIdentifier_importPrefix_topVar() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const a = 0;
''');
await _assertConst(r'''
@@ -652,7 +651,7 @@
}
test_propertyAccess_staticField_withPrefix_const() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static const a = 0;
}
@@ -664,7 +663,7 @@
}
test_propertyAccess_staticField_withPrefix_deferred() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static const a = 0;
}
@@ -676,7 +675,7 @@
}
test_propertyAccess_staticField_withPrefix_final() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
static final a = 0;
}
@@ -698,7 +697,7 @@
}
test_propertyAccess_target_variable() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
final a = 0;
const A();
diff --git a/pkg/analyzer/test/src/dart/element/element_test.dart b/pkg/analyzer/test/src/dart/element/element_test.dart
index 8e625ec..3b0915a 100644
--- a/pkg/analyzer/test/src/dart/element/element_test.dart
+++ b/pkg/analyzer/test/src/dart/element/element_test.dart
@@ -19,7 +19,7 @@
import '../../../generated/elements_types_mixin.dart';
import '../../../generated/test_analysis_context.dart';
-import '../resolution/driver_resolution.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -838,9 +838,9 @@
}
@reflectiveTest
-class ElementAnnotationImplTest extends DriverResolutionTest {
+class ElementAnnotationImplTest extends PubPackageResolutionTest {
test_computeConstantValue() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
final String f;
const A(this.f);
@@ -1039,7 +1039,7 @@
}
@reflectiveTest
-class FieldElementImplTest extends DriverResolutionTest {
+class FieldElementImplTest extends PubPackageResolutionTest {
test_isEnumConstant() async {
await resolveTestCode(r'''
enum B {B1, B2, B3}
@@ -2213,9 +2213,9 @@
}
@reflectiveTest
-class TopLevelVariableElementImplTest extends DriverResolutionTest {
+class TopLevelVariableElementImplTest extends PubPackageResolutionTest {
test_computeConstantValue() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const int C = 42;
''');
await resolveTestCode(r'''
diff --git a/pkg/analyzer/test/src/dart/element/inheritance_manager3_test.dart b/pkg/analyzer/test/src/dart/element/inheritance_manager3_test.dart
index 4b3d2b9..562224c 100644
--- a/pkg/analyzer/test/src/dart/element/inheritance_manager3_test.dart
+++ b/pkg/analyzer/test/src/dart/element/inheritance_manager3_test.dart
@@ -9,8 +9,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../resolution/driver_resolution.dart';
-import '../resolution/with_null_safety_mixin.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -1045,7 +1044,7 @@
class InheritanceManager3WithNullSafetyTest extends _InheritanceManager3Base
with WithNullSafetyMixin {
test_getInheritedMap_topMerge_method() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
// @dart = 2.6
class A {
void foo({int a}) {}
@@ -1095,7 +1094,7 @@
}
test_getMember_optIn_inheritsOptIn() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
int foo(int a, int? b) => 0;
}
@@ -1119,7 +1118,7 @@
}
test_getMember_optIn_inheritsOptOut() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
// @dart = 2.6
class A {
int foo(int a, int b) => 0;
@@ -1204,7 +1203,7 @@
}
test_getMember_optOut_inheritsOptIn() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
int foo(int a, int? b) => 0;
}
@@ -1230,7 +1229,7 @@
}
test_getMember_optOut_mixesOptIn() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
int foo(int a, int? b) => 0;
}
@@ -1255,12 +1254,12 @@
}
test_getMember_optOut_passOptIn() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {
int foo(int a, int? b) => 0;
}
''');
- newFile('/test/lib/b.dart', content: r'''
+ newFile('$testPackageLibPath/b.dart', content: r'''
// @dart = 2.6
import 'a.dart';
class B extends A {
@@ -1284,7 +1283,7 @@
}
}
-class _InheritanceManager3Base extends DriverResolutionTest {
+class _InheritanceManager3Base extends PubPackageResolutionTest {
InheritanceManager3 manager;
@override
diff --git a/pkg/analyzer/test/src/dart/resolution/context_collection_resolution.dart b/pkg/analyzer/test/src/dart/resolution/context_collection_resolution.dart
index 6774589..c5ac808 100644
--- a/pkg/analyzer/test/src/dart/resolution/context_collection_resolution.dart
+++ b/pkg/analyzer/test/src/dart/resolution/context_collection_resolution.dart
@@ -9,6 +9,8 @@
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
+import 'package:analyzer/src/dart/analysis/driver.dart';
+import 'package:analyzer/src/dart/analysis/driver_based_analysis_context.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl;
import 'package:analyzer/src/test_utilities/mock_sdk.dart';
@@ -76,25 +78,62 @@
}
}
+class BazelWorkspaceResolutionTest extends ContextResolutionTest {
+ @override
+ List<String> get collectionIncludedPaths => [workspaceRootPath];
+
+ String get myPackageLibPath => '$myPackageRootPath/lib';
+
+ String get myPackageRootPath => '$workspaceRootPath/dart/my';
+
+ @override
+ String get testFilePath => '$myPackageLibPath/my.dart';
+
+ String get workspaceRootPath => '/workspace';
+
+ @override
+ void setUp() {
+ super.setUp();
+ newFile('$workspaceRootPath/WORKSPACE', content: '');
+ }
+}
+
/// [AnalysisContextCollection] based implementation of [ResolutionTest].
abstract class ContextResolutionTest
with ResourceProviderMixin, ResolutionTest {
static bool _lintRulesAreRegistered = false;
+ Map<String, String> _declaredVariables = {};
AnalysisContextCollection _analysisContextCollection;
List<MockSdkLibrary> get additionalMockSdkLibraries => [];
List<String> get collectionIncludedPaths;
+ set declaredVariables(Map<String, String> map) {
+ if (_analysisContextCollection != null) {
+ throw StateError('Declared variables cannot be changed after analysis.');
+ }
+
+ _declaredVariables = map;
+ }
+
AnalysisContext contextFor(String path) {
if (_analysisContextCollection == null) {
_createAnalysisContexts();
}
+ path = convertPath(path);
return _analysisContextCollection.contextFor(path);
}
+ /// TODO(scheglov) Replace this with a method that changes a file in
+ /// [AnalysisContextCollectionImpl].
+ AnalysisDriver driverFor(String path) {
+ var context = contextFor(path) as DriverBasedAnalysisContext;
+ return context.driver;
+ }
+
@override
File newFile(String path, {String content = ''}) {
if (_analysisContextCollection != null && !path.endsWith('.dart')) {
@@ -127,8 +166,9 @@
/// Create all analysis contexts in [collectionIncludedPaths].
void _createAnalysisContexts() {
_analysisContextCollection = AnalysisContextCollectionImpl(
- includedPaths: collectionIncludedPaths.map(convertPath).toList(),
+ declaredVariables: _declaredVariables,
enableIndex: true,
+ includedPaths: collectionIncludedPaths.map(convertPath).toList(),
resourceProvider: resourceProvider,
sdkPath: convertPath('/sdk'),
);
@@ -184,12 +224,23 @@
);
}
- void writeTestPackageConfigWithMeta() {
- var path = '/packages/meta';
+ void writeTestPackageConfigWith(
+ Map<String, String> nameToRootPath, {
+ bool meta = false,
+ }) {
+ var metaPath = '/packages/meta';
PackagesContent.addMetaPackageFiles(
- getFolder(path),
+ getFolder(metaPath),
);
- writeTestPackageConfig({'meta': path});
+
+ writeTestPackageConfig({
+ if (meta) 'meta': metaPath,
+ ...nameToRootPath,
+ });
+ }
+
+ void writeTestPackageConfigWithMeta() {
+ writeTestPackageConfigWith({}, meta: true);
}
}
diff --git a/pkg/analyzer/test/src/dart/resolution/export_test.dart b/pkg/analyzer/test/src/dart/resolution/export_test.dart
index 8fcf08b..fe41eaf 100644
--- a/pkg/analyzer/test/src/dart/resolution/export_test.dart
+++ b/pkg/analyzer/test/src/dart/resolution/export_test.dart
@@ -2,11 +2,10 @@
// 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/declared_variables.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'driver_resolution.dart';
+import 'context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -15,16 +14,16 @@
}
@reflectiveTest
-class ExportResolutionTest extends DriverResolutionTest {
+class ExportResolutionTest extends PubPackageResolutionTest {
test_configurations_default() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'false',
'dart.library.io': 'false',
- });
+ };
await assertNoErrorsInCode(r'''
export 'a.dart'
@@ -45,14 +44,14 @@
}
test_configurations_first() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'true',
'dart.library.io': 'false',
- });
+ };
await assertNoErrorsInCode(r'''
export 'a.dart'
@@ -73,14 +72,14 @@
}
test_configurations_second() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'false',
'dart.library.io': 'true',
- });
+ };
await assertNoErrorsInCode(r'''
export 'a.dart'
@@ -102,7 +101,7 @@
/// Test that both getter and setter are in the export namespace.
test_namespace_getter_setter() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
get f => null;
set f(_) {}
''');
@@ -113,9 +112,4 @@
expect(exportNamespace.get('f'), isNotNull);
expect(exportNamespace.get('f='), isNotNull);
}
-
- void _setDeclaredVariables(Map<String, String> map) {
- driver.declaredVariables = DeclaredVariables.fromMap(map);
- driver.configure();
- }
}
diff --git a/pkg/analyzer/test/src/dart/resolution/import_test.dart b/pkg/analyzer/test/src/dart/resolution/import_test.dart
index 78a4392..145bae8 100644
--- a/pkg/analyzer/test/src/dart/resolution/import_test.dart
+++ b/pkg/analyzer/test/src/dart/resolution/import_test.dart
@@ -2,10 +2,9 @@
// 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/declared_variables.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'driver_resolution.dart';
+import 'context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -14,16 +13,16 @@
}
@reflectiveTest
-class ImportDirectiveResolutionTest extends DriverResolutionTest {
+class ImportDirectiveResolutionTest extends PubPackageResolutionTest {
test_configurations_default() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'false',
'dart.library.io': 'false',
- });
+ };
await assertNoErrorsInCode(r'''
import 'a.dart'
@@ -44,14 +43,14 @@
}
test_configurations_first() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'true',
'dart.library.io': 'false',
- });
+ };
await assertNoErrorsInCode(r'''
import 'a.dart'
@@ -72,14 +71,14 @@
}
test_configurations_second() async {
- newFile('/test/lib/a.dart', content: 'class A {}');
- newFile('/test/lib/a_html.dart', content: 'class A {}');
- newFile('/test/lib/a_io.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_html.dart', content: 'class A {}');
+ newFile('$testPackageLibPath/a_io.dart', content: 'class A {}');
- _setDeclaredVariables({
+ declaredVariables = {
'dart.library.html': 'false',
'dart.library.io': 'true',
- });
+ };
await assertNoErrorsInCode(r'''
import 'a.dart'
@@ -98,9 +97,4 @@
var a = findElement.topVar('a');
assertElementLibraryUri(a.type.element, 'package:test/a_io.dart');
}
-
- void _setDeclaredVariables(Map<String, String> map) {
- driver.declaredVariables = DeclaredVariables.fromMap(map);
- driver.configure();
- }
}
diff --git a/pkg/analyzer/test/src/dart/resolution/library_element_test.dart b/pkg/analyzer/test/src/dart/resolution/library_element_test.dart
index 0a5c22b..3df95f6 100644
--- a/pkg/analyzer/test/src/dart/resolution/library_element_test.dart
+++ b/pkg/analyzer/test/src/dart/resolution/library_element_test.dart
@@ -2,14 +2,13 @@
// 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/src/context/packages.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:meta/meta.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'driver_resolution.dart';
+import 'context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -18,9 +17,9 @@
}
@reflectiveTest
-class LibraryElementTest extends DriverResolutionTest {
+class LibraryElementTest extends PubPackageResolutionTest {
test_languageVersion() async {
- newFile('/test/.dart_tool/package_config.json', content: '''
+ newFile('$testPackageRootPath/.dart_tool/package_config.json', content: '''
{
"configVersion": 2,
"packages": [
@@ -38,89 +37,83 @@
]
}
''');
- driver.configure(
- packages: findPackagesFrom(
- resourceProvider,
- getFolder('/test'),
- ),
- );
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
class A {}
''');
- newFile('/test/lib/b.dart', content: r'''
+ newFile('$testPackageLibPath/b.dart', content: r'''
// @dart = 2.6
class A {}
''');
- newFile('/test/lib/c.dart', content: r'''
+ newFile('$testPackageLibPath/c.dart', content: r'''
// @dart = 2.9
class A {}
''');
- newFile('/test/lib/d.dart', content: r'''
+ newFile('$testPackageLibPath/d.dart', content: r'''
// @dart = 2.99
class A {}
''');
- newFile('/test/lib/e.dart', content: r'''
+ newFile('$testPackageLibPath/e.dart', content: r'''
// @dart = 3.0
class A {}
''');
- newFile('/aaa/lib/a.dart', content: r'''
+ newFile('$workspaceRootPath/aaa/lib/a.dart', content: r'''
class A {}
''');
- newFile('/aaa/lib/b.dart', content: r'''
+ newFile('$workspaceRootPath/aaa/lib/b.dart', content: r'''
// @dart = 2.99
class A {}
''');
- newFile('/aaa/lib/c.dart', content: r'''
+ newFile('$workspaceRootPath/aaa/lib/c.dart', content: r'''
// @dart = 3.0
class A {}
''');
// No override.
await _assertLanguageVersion(
- uriStr: 'package:test/a.dart',
+ path: '$testPackageLibPath/a.dart',
package: Version.parse('2.7.0'),
override: null,
);
// Valid override, less than the latest supported language version.
await _assertLanguageVersion(
- uriStr: 'package:test/b.dart',
+ path: '$testPackageLibPath/b.dart',
package: Version.parse('2.7.0'),
override: Version.parse('2.6.0'),
);
// Valid override, even if greater than the package language version.
await _assertLanguageVersion(
- uriStr: 'package:test/c.dart',
+ path: '$testPackageLibPath/c.dart',
package: Version.parse('2.7.0'),
override: Version.parse('2.9.0'),
);
// Invalid override: minor is greater than the latest minor.
await _assertLanguageVersion(
- uriStr: 'package:test/d.dart',
+ path: '$testPackageLibPath/d.dart',
package: Version.parse('2.7.0'),
override: null,
);
// Invalid override: major is greater than the latest major.
await _assertLanguageVersion(
- uriStr: 'package:test/e.dart',
+ path: '$testPackageLibPath/e.dart',
package: Version.parse('2.7.0'),
override: null,
);
- await _assertLanguageVersionCurrent('package:aaa/a.dart');
- await _assertLanguageVersionCurrent('package:aaa/b.dart');
- await _assertLanguageVersionCurrent('package:aaa/c.dart');
+ await _assertLanguageVersionCurrent('$workspaceRootPath/aaa/lib/a.dart');
+ await _assertLanguageVersionCurrent('$workspaceRootPath/aaa/lib/b.dart');
+ await _assertLanguageVersionCurrent('$workspaceRootPath/aaa/lib/c.dart');
}
test_scope_lookup2() async {
@@ -373,18 +366,21 @@
}
Future<void> _assertLanguageVersion({
- @required String uriStr,
+ @required String path,
@required Version package,
@required Version override,
}) async {
- var element = await driver.getLibraryByUri(uriStr);
+ path = convertPath(path);
+ var session = contextFor(path).currentSession;
+ var file = session.getFile(path);
+ var element = await session.getLibraryByUri('${file.uri}');
expect(element.languageVersion.package, package);
expect(element.languageVersion.override, override);
}
- Future<void> _assertLanguageVersionCurrent(String uriStr) async {
+ Future<void> _assertLanguageVersionCurrent(String path) async {
await _assertLanguageVersion(
- uriStr: uriStr,
+ path: path,
package: ExperimentStatus.currentVersion,
override: null,
);
diff --git a/pkg/analyzer/test/src/dart/resolution/non_nullable_bazel_workspace_test.dart b/pkg/analyzer/test/src/dart/resolution/non_nullable_bazel_workspace_test.dart
new file mode 100644
index 0000000..517ad52
--- /dev/null
+++ b/pkg/analyzer/test/src/dart/resolution/non_nullable_bazel_workspace_test.dart
@@ -0,0 +1,110 @@
+// Copyright (c) 2020, 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:test_reflective_loader/test_reflective_loader.dart';
+
+import 'context_collection_resolution.dart';
+
+main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(NonNullableBazelWorkspaceTest);
+ });
+}
+
+@reflectiveTest
+class NonNullableBazelWorkspaceTest extends BazelWorkspaceResolutionTest {
+ @override
+ bool get typeToStringWithNullability => true;
+
+ test_buildFile_legacy_commentedOut() async {
+ newFile('$myPackageRootPath/BUILD', content: r'''
+dart_package(
+# null_safety = True,
+''');
+
+ await resolveFileCode(
+ '$myPackageRootPath/lib/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int*');
+ }
+
+ test_buildFile_nonNullable() async {
+ newFile('$myPackageRootPath/BUILD', content: r'''
+dart_package(
+ null_safety = True,
+)
+''');
+
+ // Non-nullable in lib/.
+ await resolveFileCode(
+ '$myPackageRootPath/lib/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int');
+
+ // Non-nullable in test/.
+ await resolveFileCode(
+ '$myPackageRootPath/test/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int');
+
+ // Non-nullable in bin/.
+ await resolveFileCode(
+ '$myPackageRootPath/bin/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int');
+
+ // Legacy in other package.
+ await resolveFileCode(
+ '$workspaceRootPath/dart/aaa/lib/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int*');
+ }
+
+ test_buildFile_nonNullable_oneLine_noComma() async {
+ newFile('$myPackageRootPath/BUILD', content: r'''
+dart_package(null_safety = True)
+''');
+
+ await resolveFileCode(
+ '$myPackageRootPath/lib/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int');
+ }
+
+ test_buildFile_nonNullable_withComments() async {
+ newFile('$myPackageRootPath/BUILD', content: r'''
+dart_package(
+ # Preceding comment.
+ null_safety = True, # Trailing comment.
+) # Last comment.
+''');
+
+ await resolveFileCode(
+ '$myPackageRootPath/lib/a.dart',
+ 'int v = 0;',
+ );
+ assertNoErrorsInResult();
+ assertType(findNode.typeName('int v'), 'int');
+ }
+
+ test_noBuildFile_legacy() async {
+ await assertNoErrorsInCode('''
+int v = 0;
+''');
+
+ assertType(findNode.typeName('int v'), 'int*');
+ }
+}
diff --git a/pkg/analyzer/test/src/dart/resolution/resolution.dart b/pkg/analyzer/test/src/dart/resolution/resolution.dart
index a592c91..5aa6ff0 100644
--- a/pkg/analyzer/test/src/dart/resolution/resolution.dart
+++ b/pkg/analyzer/test/src/dart/resolution/resolution.dart
@@ -291,6 +291,10 @@
assertErrorsInList(result.errors, expectedErrors);
}
+ void assertErrorsInResult(List<ExpectedError> expectedErrors) {
+ assertErrorsInResolvedUnit(result, expectedErrors);
+ }
+
void assertFunctionExpressionInvocation(
FunctionExpressionInvocation node, {
@required ExecutableElement element,
@@ -516,6 +520,10 @@
assertErrorsInResolvedUnit(result, const []);
}
+ void assertNoErrorsInResult() {
+ assertErrorsInResult(const []);
+ }
+
void assertParameterElement(
Expression expression,
ParameterElement expected,
@@ -767,19 +775,33 @@
Future<ResolvedUnitResult> resolveFile(String path);
- /// Put the [code] into the test file, and resolve it.
- Future<void> resolveTestCode(String code) async {
- addTestFile(code);
- await resolveTestFile();
- }
+ /// Resolve the file with the [path] into [result].
+ Future<void> resolveFile2(String path) async {
+ path = convertPath(path);
- Future<void> resolveTestFile() async {
- var path = convertPath(testFilePath);
result = await resolveFile(path);
+ expect(result.state, ResultState.VALID);
+
findNode = FindNode(result.content, result.unit);
findElement = FindElement(result.unit);
}
+ /// Create a new file with the [path] and [content], resolve it into [result].
+ Future<void> resolveFileCode(String path, String content) {
+ newFile(path, content: content);
+ return resolveFile2(path);
+ }
+
+ /// Put the [code] into the test file, and resolve it.
+ Future<void> resolveTestCode(String code) {
+ addTestFile(code);
+ return resolveTestFile();
+ }
+
+ Future<void> resolveTestFile() {
+ return resolveFile2(testFilePath);
+ }
+
/// Choose the type display string, depending on whether the [result] is
/// non-nullable or legacy.
String typeStr(String nonNullable, String legacy) {
diff --git a/pkg/analyzer/test/src/dart/resolution/test_all.dart b/pkg/analyzer/test/src/dart/resolution/test_all.dart
index 1b33b1b..7c87fe5 100644
--- a/pkg/analyzer/test/src/dart/resolution/test_all.dart
+++ b/pkg/analyzer/test/src/dart/resolution/test_all.dart
@@ -46,6 +46,7 @@
import 'method_invocation_test.dart' as method_invocation;
import 'mixin_test.dart' as mixin_resolution;
import 'namespace_test.dart' as namespace;
+import 'non_nullable_bazel_workspace_test.dart' as non_nullable_bazel_workspace;
import 'non_nullable_test.dart' as non_nullable;
import 'optional_const_test.dart' as optional_const;
import 'postfix_expression_test.dart' as postfix_expression;
@@ -102,6 +103,7 @@
method_invocation.main();
mixin_resolution.main();
namespace.main();
+ non_nullable_bazel_workspace.main();
non_nullable.main();
optional_const.main();
postfix_expression.main();
diff --git a/pkg/analyzer/test/src/dart/resolver/exit_detector_test.dart b/pkg/analyzer/test/src/dart/resolver/exit_detector_test.dart
index d9b7c1b..e60d05c 100644
--- a/pkg/analyzer/test/src/dart/resolver/exit_detector_test.dart
+++ b/pkg/analyzer/test/src/dart/resolver/exit_detector_test.dart
@@ -9,7 +9,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../ast/parse_base.dart';
-import '../resolution/driver_resolution.dart';
+import '../resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -920,7 +920,7 @@
/// TODO(paulberry): migrate this test away from the task model.
/// See dartbug.com/35734.
@reflectiveTest
-class ExitDetectorResolvedStatementTest extends DriverResolutionTest {
+class ExitDetectorResolvedStatementTest extends PubPackageResolutionTest {
test_forStatement_implicitTrue_breakWithLabel() async {
await _assertNthStatementDoesNotExit(r'''
void f() {
@@ -1081,15 +1081,9 @@
}
Future<void> _assertHasReturn(String code, int n, bool expected) async {
- var path = convertPath('/test/lib/test.dart');
+ await resolveTestCode(code);
- newFile(path, content: code);
-
- var session = driver.currentSession;
- var resolvedResult = await session.getResolvedUnit(path);
-
- var unit = resolvedResult.unit;
- FunctionDeclaration function = unit.declarations.last;
+ FunctionDeclaration function = result.unit.declarations.last;
BlockFunctionBody body = function.functionExpression.body;
Statement statement = body.block.statements[n];
expect(ExitDetector.exits(statement), expected);
diff --git a/pkg/analyzer/test/src/diagnostics/abstract_field_constructor_initializer_test.dart b/pkg/analyzer/test/src/diagnostics/abstract_field_constructor_initializer_test.dart
new file mode 100644
index 0000000..b874331
--- /dev/null
+++ b/pkg/analyzer/test/src/diagnostics/abstract_field_constructor_initializer_test.dart
@@ -0,0 +1,80 @@
+// Copyright (c) 2020, 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/src/error/codes.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import '../dart/resolution/context_collection_resolution.dart';
+
+main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(AbstractFieldConstructorInitializerTest);
+ });
+}
+
+@reflectiveTest
+class AbstractFieldConstructorInitializerTest extends PubPackageResolutionTest
+ with WithNullSafetyMixin {
+ test_abstract_field_constructor_initializer() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+ A() : x = 0;
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER, 45, 1),
+ ]);
+ }
+
+ test_abstract_field_final_constructor_initializer() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x;
+ A() : x = 0;
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER, 51, 1),
+ ]);
+ }
+
+ test_abstract_field_final_initializing_formal() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x;
+ A(this.x);
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER, 52, 1),
+ ]);
+ }
+
+ test_abstract_field_final_no_initialization() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+ A();
+}
+''');
+ }
+
+ test_abstract_field_initializing_formal() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+ A(this.x);
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_CONSTRUCTOR_INITIALIZER, 46, 1),
+ ]);
+ }
+
+ test_abstract_field_no_initialization() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+ A();
+}
+''');
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/abstract_field_initializer_test.dart b/pkg/analyzer/test/src/diagnostics/abstract_field_initializer_test.dart
new file mode 100644
index 0000000..417c2d6
--- /dev/null
+++ b/pkg/analyzer/test/src/diagnostics/abstract_field_initializer_test.dart
@@ -0,0 +1,54 @@
+// Copyright (c) 2020, 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/src/error/codes.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import '../dart/resolution/context_collection_resolution.dart';
+
+main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(AbstractFieldInitializerTest);
+ });
+}
+
+@reflectiveTest
+class AbstractFieldInitializerTest extends PubPackageResolutionTest
+ with WithNullSafetyMixin {
+ test_abstract_field_final_initializer() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x = 0;
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_INITIALIZER, 40, 1),
+ ]);
+ }
+
+ test_abstract_field_final_no_initializer() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+''');
+ }
+
+ test_abstract_field_initializer() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x = 0;
+}
+''', [
+ error(CompileTimeErrorCode.ABSTRACT_FIELD_INITIALIZER, 34, 1),
+ ]);
+ }
+
+ test_abstract_field_no_initializer() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+''');
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/assignment_to_final_test.dart b/pkg/analyzer/test/src/diagnostics/assignment_to_final_test.dart
index bbe22a6..b93d824 100644
--- a/pkg/analyzer/test/src/diagnostics/assignment_to_final_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/assignment_to_final_test.dart
@@ -71,4 +71,31 @@
}
''');
}
+
+ test_set_abstract_field_final_invalid() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+void f(A a, int x) {
+ a.x = x;
+}
+''', [
+ error(CompileTimeErrorCode.ASSIGNMENT_TO_FINAL, 70, 1),
+ ]);
+ }
+
+ test_set_abstract_field_final_overridden_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+abstract class B extends A {
+ void set x(int value);
+}
+void f(B b, int x) {
+ b.x = x; // ok because setter provided in derived class
+}
+''');
+ }
}
diff --git a/pkg/analyzer/test/src/diagnostics/concrete_class_with_abstract_member_test.dart b/pkg/analyzer/test/src/diagnostics/concrete_class_with_abstract_member_test.dart
index 77805ab..c85acdb 100644
--- a/pkg/analyzer/test/src/diagnostics/concrete_class_with_abstract_member_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/concrete_class_with_abstract_member_test.dart
@@ -10,11 +10,15 @@
main() {
defineReflectiveSuite(() {
defineReflectiveTests(ConcreteClassWithAbstractMemberTest);
+ defineReflectiveTests(ConcreteClassWithAbstractMemberWithNullSafetyTest);
});
}
@reflectiveTest
-class ConcreteClassWithAbstractMemberTest extends PubPackageResolutionTest {
+class ConcreteClassWithAbstractMemberTest extends PubPackageResolutionTest
+ with ConcreteClassWithAbstractMemberTestCases {}
+
+mixin ConcreteClassWithAbstractMemberTestCases on PubPackageResolutionTest {
test_direct() async {
await assertErrorsInCode('''
class A {
@@ -36,3 +40,32 @@
]);
}
}
+
+@reflectiveTest
+class ConcreteClassWithAbstractMemberWithNullSafetyTest
+ extends PubPackageResolutionTest
+ with WithNullSafetyMixin, ConcreteClassWithAbstractMemberTestCases {
+ test_abstract_field() async {
+ await assertErrorsInCode('''
+class A {
+ abstract int? x;
+}
+''', [
+ error(CompileTimeErrorCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, 12, 16,
+ text: "'x' must have a method body because 'A' isn't abstract."),
+ error(CompileTimeErrorCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, 12, 16,
+ text: "'x=' must have a method body because 'A' isn't abstract."),
+ ]);
+ }
+
+ test_abstract_field_final() async {
+ await assertErrorsInCode('''
+class A {
+ abstract final int? x;
+}
+''', [
+ error(CompileTimeErrorCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER, 12, 22,
+ text: "'x' must have a method body because 'A' isn't abstract."),
+ ]);
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/const_eval_throws_exception_test.dart b/pkg/analyzer/test/src/diagnostics/const_eval_throws_exception_test.dart
index b7517ec..54cccca 100644
--- a/pkg/analyzer/test/src/diagnostics/const_eval_throws_exception_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/const_eval_throws_exception_test.dart
@@ -2,7 +2,6 @@
// 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/declared_variables.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/error/codes.dart';
@@ -10,8 +9,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../dart/resolution/driver_resolution.dart';
-import '../dart/resolution/with_null_safety_mixin.dart';
+import '../dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -22,7 +20,7 @@
}
@reflectiveTest
-class ConstEvalThrowsExceptionTest extends DriverResolutionTest {
+class ConstEvalThrowsExceptionTest extends PubPackageResolutionTest {
test_assertInitializerThrows() async {
await assertErrorsInCode(r'''
class A {
@@ -36,7 +34,7 @@
test_CastError_intToDouble_constructor_importAnalyzedAfter() async {
// See dartbug.com/35993
- newFile('/test/lib/other.dart', content: '''
+ newFile('$testPackageLibPath/other.dart', content: '''
class Foo {
final double value;
@@ -60,13 +58,13 @@
}
''');
var otherFileResult =
- await resolveFile(convertPath('/test/lib/other.dart'));
+ await resolveFile(convertPath('$testPackageLibPath/other.dart'));
expect(otherFileResult.errors, isEmpty);
}
test_CastError_intToDouble_constructor_importAnalyzedBefore() async {
// See dartbug.com/35993
- newFile('/test/lib/other.dart', content: '''
+ newFile('$testPackageLibPath/other.dart', content: '''
class Foo {
final double value;
@@ -90,12 +88,12 @@
}
''');
var otherFileResult =
- await resolveFile(convertPath('/test/lib/other.dart'));
+ await resolveFile(convertPath('$testPackageLibPath/other.dart'));
expect(otherFileResult.errors, isEmpty);
}
test_default_constructor_arg_empty_map_import() async {
- newFile('/test/lib/other.dart', content: '''
+ newFile('$testPackageLibPath/other.dart', content: '''
class C {
final Map<String, int> m;
const C({this.m = const <String, int>{}})
@@ -112,7 +110,7 @@
error(HintCode.UNUSED_LOCAL_VARIABLE, 37, 1),
]);
var otherFileResult =
- await resolveFile(convertPath('/test/lib/other.dart'));
+ await resolveFile(convertPath('$testPackageLibPath/other.dart'));
assertErrorsInList(
otherFileResult.errors,
expectedErrorsByNullability(
@@ -193,7 +191,7 @@
test_fromEnvironment_bool_badDefault_whenDefined() async {
// The type of the defaultValue needs to be correct even when the default
// value isn't used (because the variable is defined in the environment).
- driver.declaredVariables = DeclaredVariables.fromMap({'x': 'true'});
+ declaredVariables = {'x': 'true'};
await assertErrorsInCode('''
var b = const bool.fromEnvironment('x', defaultValue: 1);
''', [
@@ -277,7 +275,7 @@
}
test_invalid_constructorFieldInitializer_fromSeparateLibrary() async {
- newFile('/test/lib/lib.dart', content: r'''
+ newFile('$testPackageLibPath/lib.dart', content: r'''
class A<T> {
final int f;
const A() : f = T.foo;
diff --git a/pkg/analyzer/test/src/diagnostics/deprecated_member_use_test.dart b/pkg/analyzer/test/src/diagnostics/deprecated_member_use_test.dart
index 8a43e70..c273957 100644
--- a/pkg/analyzer/test/src/diagnostics/deprecated_member_use_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/deprecated_member_use_test.dart
@@ -362,8 +362,8 @@
configureWorkspace(root: '/workspace');
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
- newFileWithBytes('/workspace/.packages', 'project:lib/'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
+ newFile('/workspace/.packages', content: 'project:lib/');
newFile('/workspace/lib/deprecated_library.dart', content: r'''
@deprecated
@@ -707,7 +707,7 @@
''');
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
await assertErrorsInFile('/workspace/package/lib/lib1.dart', r'''
import 'package:aaa/a.dart';
diff --git a/pkg/analyzer/test/src/diagnostics/final_not_initialized_test.dart b/pkg/analyzer/test/src/diagnostics/final_not_initialized_test.dart
index 7e55627..8772ebf 100644
--- a/pkg/analyzer/test/src/diagnostics/final_not_initialized_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/final_not_initialized_test.dart
@@ -11,6 +11,7 @@
main() {
defineReflectiveSuite(() {
defineReflectiveTests(FinalNotInitializedTest);
+ defineReflectiveTests(FinalNotInitializedWithNullSafetyTest);
});
}
@@ -84,6 +85,23 @@
@reflectiveTest
class FinalNotInitializedWithNullSafetyTest extends PubPackageResolutionTest
with WithNullSafetyMixin {
+ test_field_abstract() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+''');
+ }
+
+ test_field_abstract_with_constructor() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+ A();
+}
+''');
+ }
+
test_field_noConstructor_initializer() async {
await assertNoErrorsInCode('''
class C {
diff --git a/pkg/analyzer/test/src/diagnostics/invalid_language_override_greater_test.dart b/pkg/analyzer/test/src/diagnostics/invalid_language_override_greater_test.dart
index 53609b5..03e35bc 100644
--- a/pkg/analyzer/test/src/diagnostics/invalid_language_override_greater_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/invalid_language_override_greater_test.dart
@@ -2,7 +2,6 @@
// 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/src/context/packages.dart';
import 'package:analyzer/src/dart/analysis/experiments.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/error/hint_codes.dart';
@@ -11,8 +10,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../dart/resolution/driver_resolution.dart';
-import '../dart/resolution/with_null_safety_mixin.dart';
+import '../dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -21,7 +19,7 @@
}
@reflectiveTest
-class InvalidLanguageOverrideGreaterTest extends DriverResolutionTest
+class InvalidLanguageOverrideGreaterTest extends PubPackageResolutionTest
with WithNullSafetyMixin {
test_greaterThanLatest() async {
var latestVersion = ExperimentStatus.currentVersion;
@@ -72,15 +70,18 @@
}
void _configureTestPackageLanguageVersion(String versionStr) {
- driver.configure(
- packages: Packages({
- 'test': Package(
- name: 'test',
- rootFolder: getFolder('/test'),
- libFolder: getFolder('/test/lib'),
- languageVersion: Version.parse(versionStr + '.0'),
- ),
- }),
- );
+ newFile('$testPackageRootPath/.dart_tool/package_config.json', content: '''
+{
+ "configVersion": 2,
+ "packages": [
+ {
+ "name": "test",
+ "rootUri": "../",
+ "packageUri": "lib/",
+ "languageVersion": "$versionStr"
+ }
+ ]
+}
+''');
}
}
diff --git a/pkg/analyzer/test/src/diagnostics/invalid_override_test.dart b/pkg/analyzer/test/src/diagnostics/invalid_override_test.dart
index 6809dfa..fc35f34 100644
--- a/pkg/analyzer/test/src/diagnostics/invalid_override_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/invalid_override_test.dart
@@ -562,6 +562,96 @@
@reflectiveTest
class InvalidOverrideWithNullSafetyTest extends PubPackageResolutionTest
with WithNullSafetyMixin {
+ test_abstract_field_covariant_inheritance() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract covariant num x;
+}
+abstract class B implements A {
+ void set x(Object value); // Implicitly covariant
+}
+abstract class C implements B {
+ int get x;
+ void set x(int value); // Ok because covariant
+}
+''');
+ }
+
+ test_getter_overrides_abstract_field_covariant_invalid() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract covariant int x;
+}
+abstract class B implements A {
+ num get x;
+ void set x(num value);
+}
+''', [
+ error(CompileTimeErrorCode.INVALID_OVERRIDE, 91, 1),
+ ]);
+ }
+
+ test_getter_overrides_abstract_field_covariant_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract covariant num x;
+}
+abstract class B implements A {
+ int get x;
+}
+''');
+ }
+
+ test_getter_overrides_abstract_field_final_invalid() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+abstract class B implements A {
+ num get x;
+ void set x(num value);
+}
+''', [
+ error(CompileTimeErrorCode.INVALID_OVERRIDE, 87, 1),
+ ]);
+ }
+
+ test_getter_overrides_abstract_field_final_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final num x;
+}
+abstract class B implements A {
+ int get x;
+}
+''');
+ }
+
+ test_getter_overrides_abstract_field_invalid() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+abstract class B implements A {
+ num get x;
+ void set x(num value);
+}
+''', [
+ error(CompileTimeErrorCode.INVALID_OVERRIDE, 81, 1),
+ ]);
+ }
+
+ test_getter_overrides_abstract_field_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract num x;
+}
+abstract class B implements A {
+ int get x;
+}
+''');
+ }
+
test_method_parameter_functionTyped_optOut_extends_optIn() async {
newFile('$testPackageLibPath/a.dart', content: r'''
abstract class A {
@@ -659,6 +749,55 @@
''');
}
+ test_setter_overrides_abstract_field_covariant_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract covariant num x;
+}
+abstract class B implements A {
+ int get x;
+ void set x(int value);
+}
+''');
+ }
+
+ test_setter_overrides_abstract_field_final_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final num x;
+}
+abstract class B implements A {
+ int get x;
+ void set x(int value);
+}
+''');
+ }
+
+ test_setter_overrides_abstract_field_invalid() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract num x;
+}
+abstract class B implements A {
+ int get x;
+ void set x(int value);
+}
+''', [
+ error(CompileTimeErrorCode.INVALID_OVERRIDE, 95, 1),
+ ]);
+ }
+
+ test_setter_overrides_abstract_field_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+abstract class B implements A {
+ void set x(num value);
+}
+''');
+ }
+
test_viaLegacy_class() async {
newFile('$testPackageLibPath/a.dart', content: r'''
class A1 {
diff --git a/pkg/analyzer/test/src/diagnostics/non_abstract_class_inherits_abstract_member_test.dart b/pkg/analyzer/test/src/diagnostics/non_abstract_class_inherits_abstract_member_test.dart
index 1394130..c2faa10 100644
--- a/pkg/analyzer/test/src/diagnostics/non_abstract_class_inherits_abstract_member_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/non_abstract_class_inherits_abstract_member_test.dart
@@ -10,12 +10,18 @@
main() {
defineReflectiveSuite(() {
defineReflectiveTests(NonAbstractClassInheritsAbstractMemberTest);
+ defineReflectiveTests(
+ NonAbstractClassInheritsAbstractMemberWithNullSafetyTest);
});
}
@reflectiveTest
class NonAbstractClassInheritsAbstractMemberTest
- extends PubPackageResolutionTest {
+ extends PubPackageResolutionTest
+ with NonAbstractClassInheritsAbstractMemberTestCases {}
+
+mixin NonAbstractClassInheritsAbstractMemberTestCases
+ on PubPackageResolutionTest {
test_abstractsDontOverrideConcretes_getter() async {
await assertNoErrorsInCode(r'''
class A {
@@ -606,3 +612,91 @@
]);
}
}
+
+@reflectiveTest
+class NonAbstractClassInheritsAbstractMemberWithNullSafetyTest
+ extends PubPackageResolutionTest
+ with WithNullSafetyMixin, NonAbstractClassInheritsAbstractMemberTestCases {
+ test_abstract_field_final_implement_getter() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+class B implements A {
+ int get x => 0;
+}
+''');
+ }
+
+ test_abstract_field_final_implement_none() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+class B implements A {}
+''', [
+ error(
+ CompileTimeErrorCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
+ 51,
+ 1),
+ ]);
+ }
+
+ test_abstract_field_implement_getter() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+class B implements A {
+ int get x => 0;
+}
+''', [
+ error(
+ CompileTimeErrorCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
+ 45,
+ 1),
+ ]);
+ }
+
+ test_abstract_field_implement_getter_and_setter() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+class B implements A {
+ int get x => 0;
+ void set x(int value) {}
+}
+''');
+ }
+
+ test_abstract_field_implement_none() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+class B implements A {}
+''', [
+ error(
+ CompileTimeErrorCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO,
+ 45,
+ 1),
+ ]);
+ }
+
+ test_abstract_field_implement_setter() async {
+ await assertErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+class B implements A {
+ void set x(int value) {}
+}
+''', [
+ error(
+ CompileTimeErrorCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
+ 45,
+ 1),
+ ]);
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/not_initialized_non_nullable_instance_field_test.dart b/pkg/analyzer/test/src/diagnostics/not_initialized_non_nullable_instance_field_test.dart
index 1b62195..08e6965 100644
--- a/pkg/analyzer/test/src/diagnostics/not_initialized_non_nullable_instance_field_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/not_initialized_non_nullable_instance_field_test.dart
@@ -16,6 +16,23 @@
@reflectiveTest
class NotInitializedNonNullableInstanceFieldTest
extends PubPackageResolutionTest with WithNullSafetyMixin {
+ test_abstract_field_non_nullable() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+''');
+ }
+
+ test_abstract_field_non_nullable_with_constructor() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+ A();
+}
+''');
+ }
+
test_class_factoryConstructor() async {
await assertNoErrorsInCode('''
class A {
diff --git a/pkg/analyzer/test/src/diagnostics/test_all.dart b/pkg/analyzer/test/src/diagnostics/test_all.dart
index 5346a05..c166314 100644
--- a/pkg/analyzer/test/src/diagnostics/test_all.dart
+++ b/pkg/analyzer/test/src/diagnostics/test_all.dart
@@ -5,6 +5,9 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'abstract_class_member_test.dart' as abstract_class_member;
+import 'abstract_field_constructor_initializer_test.dart'
+ as abstract_field_constructor_initializer;
+import 'abstract_field_initializer_test.dart' as abstract_field_initializer;
import 'abstract_super_member_reference_test.dart'
as abstract_super_member_reference;
import 'access_private_enum_field_test.dart' as access_private_enum_field;
@@ -631,6 +634,8 @@
main() {
defineReflectiveSuite(() {
abstract_class_member.main();
+ abstract_field_constructor_initializer.main();
+ abstract_field_initializer.main();
abstract_super_member_reference.main();
access_private_enum_field.main();
ambiguous_export.main();
diff --git a/pkg/analyzer/test/src/diagnostics/undefined_getter_test.dart b/pkg/analyzer/test/src/diagnostics/undefined_getter_test.dart
index a914c3c..65b9468 100644
--- a/pkg/analyzer/test/src/diagnostics/undefined_getter_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/undefined_getter_test.dart
@@ -10,11 +10,15 @@
main() {
defineReflectiveSuite(() {
defineReflectiveTests(UndefinedGetterTest);
+ defineReflectiveTests(UndefinedGetterWithNullSafetyTest);
});
}
@reflectiveTest
-class UndefinedGetterTest extends PubPackageResolutionTest {
+class UndefinedGetterTest extends PubPackageResolutionTest
+ with UndefinedGetterTestCases {}
+
+mixin UndefinedGetterTestCases on PubPackageResolutionTest {
test_compoundAssignment_hasSetter_instance() async {
await assertErrorsInCode('''
class C {
@@ -222,14 +226,19 @@
}
test_nullMember_undefined() async {
- await assertErrorsInCode(r'''
+ await assertErrorsInCode(
+ r'''
m() {
Null _null;
_null.foo;
}
-''', [
- error(CompileTimeErrorCode.UNDEFINED_GETTER, 28, 3),
- ]);
+''',
+ expectedErrorsByNullability(nullable: [
+ error(CompileTimeErrorCode.INVALID_USE_OF_NULL_VALUE, 22, 5),
+ error(CompileTimeErrorCode.UNDEFINED_GETTER, 28, 3),
+ ], legacy: [
+ error(CompileTimeErrorCode.UNDEFINED_GETTER, 28, 3),
+ ]));
}
test_object_call() async {
@@ -332,8 +341,10 @@
await assertNoErrorsInCode(r'''
class A<E> {
E element;
+ A(this.element);
}
class B extends A<List> {
+ B(List element) : super(element);
m() {
element.last;
}
@@ -341,3 +352,31 @@
''');
}
}
+
+@reflectiveTest
+class UndefinedGetterWithNullSafetyTest extends PubPackageResolutionTest
+ with WithNullSafetyMixin, UndefinedGetterTestCases {
+ test_get_from_abstract_field_final_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract final int x;
+}
+int f(A a) => a.x;
+''');
+ }
+
+ test_get_from_abstract_field_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+int f(A a) => a.x;
+''');
+ }
+
+ @override
+ @FailingTest(issue: 'https://github.com/dart-lang/sdk/issues/42957')
+ test_typeLiteral_conditionalAccess() {
+ return super.test_typeLiteral_conditionalAccess();
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/undefined_setter_test.dart b/pkg/analyzer/test/src/diagnostics/undefined_setter_test.dart
index d0d2315..d5c09b8 100644
--- a/pkg/analyzer/test/src/diagnostics/undefined_setter_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/undefined_setter_test.dart
@@ -10,11 +10,15 @@
main() {
defineReflectiveSuite(() {
defineReflectiveTests(UndefinedSetterTest);
+ defineReflectiveTests(UndefinedSetterWithNullSafetyTest);
});
}
@reflectiveTest
-class UndefinedSetterTest extends PubPackageResolutionTest {
+class UndefinedSetterTest extends PubPackageResolutionTest
+ with UndefinedSetterTestCases {}
+
+mixin UndefinedSetterTestCases on PubPackageResolutionTest {
test_importWithPrefix_defined() async {
newFile('$testPackageLibPath/lib.dart', content: r'''
library lib;
@@ -135,3 +139,18 @@
]);
}
}
+
+@reflectiveTest
+class UndefinedSetterWithNullSafetyTest extends PubPackageResolutionTest
+ with WithNullSafetyMixin, UndefinedSetterTestCases {
+ test_set_abstract_field_valid() async {
+ await assertNoErrorsInCode('''
+abstract class A {
+ abstract int x;
+}
+void f(A a, int x) {
+ a.x = x;
+}
+''');
+ }
+}
diff --git a/pkg/analyzer/test/src/diagnostics/uri_does_not_exist_test.dart b/pkg/analyzer/test/src/diagnostics/uri_does_not_exist_test.dart
index 8682a2d1..a9bdb9b 100644
--- a/pkg/analyzer/test/src/diagnostics/uri_does_not_exist_test.dart
+++ b/pkg/analyzer/test/src/diagnostics/uri_does_not_exist_test.dart
@@ -5,8 +5,7 @@
import 'package:analyzer/src/error/codes.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../generated/test_support.dart';
-import '../dart/resolution/driver_resolution.dart';
+import '../dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -15,7 +14,7 @@
}
@reflectiveTest
-class UriDoesNotExistTest extends DriverResolutionTest {
+class UriDoesNotExistTest extends PubPackageResolutionTest {
test_deferredImportWithInvalidUri() async {
await assertErrorsInCode(r'''
import '[invalid uri]' deferred as p;
@@ -44,7 +43,7 @@
}
test_import_appears_after_deleting_target() async {
- String filePath = newFile('/test/lib/target.dart').path;
+ String filePath = newFile('$testPackageLibPath/target.dart').path;
await assertErrorsInCode('''
import 'target.dart';
@@ -54,12 +53,10 @@
// Remove the overlay in the same way as AnalysisServer.
deleteFile(filePath);
- driver.removeFile(filePath);
+ driverFor(testFilePath).removeFile(filePath);
await resolveTestFile();
- GatheringErrorListener errorListener = GatheringErrorListener();
- errorListener.addAll(result.errors);
- errorListener.assertErrors([
+ assertErrorsInResult([
error(CompileTimeErrorCode.URI_DOES_NOT_EXIST, 7, 13),
]);
}
@@ -72,15 +69,13 @@
error(CompileTimeErrorCode.URI_DOES_NOT_EXIST, 7, 13),
]);
- newFile('/test/lib/target.dart');
+ newFile('$testPackageLibPath/target.dart');
// Make sure the error goes away.
// TODO(brianwilkerson) The error does not go away, possibly because the
// file is not being reanalyzed.
await resolveTestFile();
- GatheringErrorListener errorListener = GatheringErrorListener();
- errorListener.addAll(result.errors);
- errorListener.assertErrors([
+ assertErrorsInResult([
error(HintCode.UNUSED_IMPORT, 0, 0),
]);
}
@@ -95,21 +90,21 @@
}
test_valid_dll() async {
- newFile("/test/lib/lib.dll");
+ newFile("$testPackageLibPath/lib.dll");
await assertNoErrorsInCode('''
import 'dart-ext:lib';
''');
}
test_valid_dylib() async {
- newFile("/test/lib/lib.dylib");
+ newFile("$testPackageLibPath/lib.dylib");
await assertNoErrorsInCode('''
import 'dart-ext:lib';
''');
}
test_valid_so() async {
- newFile("/test/lib/lib.so");
+ newFile("$testPackageLibPath/lib.so");
await assertNoErrorsInCode('''
import 'dart-ext:lib';
''');
diff --git a/pkg/analyzer/test/src/lint/linter/linter_context_impl_test.dart b/pkg/analyzer/test/src/lint/linter/linter_context_impl_test.dart
index 01364df..194fe57 100644
--- a/pkg/analyzer/test/src/lint/linter/linter_context_impl_test.dart
+++ b/pkg/analyzer/test/src/lint/linter/linter_context_impl_test.dart
@@ -11,7 +11,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../dart/resolution/driver_resolution.dart';
+import '../../dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -24,7 +24,7 @@
}
@reflectiveTest
-abstract class AbstractLinterContextTest extends DriverResolutionTest {
+abstract class AbstractLinterContextTest extends PubPackageResolutionTest {
LinterContextImpl context;
Future<void> resolve(String content) async {
@@ -246,7 +246,7 @@
}
void test_true_computeDependencies() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const a = 0;
''');
@@ -286,7 +286,7 @@
}
void test_true_importedClass_defaultValue() async {
- var aPath = convertPath('/test/lib/a.dart');
+ var aPath = convertPath('$testPackageLibPath/a.dart');
newFile(aPath, content: r'''
class A {
final int a;
@@ -329,7 +329,7 @@
}
void test_listLiteral_true_computeDependencies() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
const a = 0;
''');
@@ -463,7 +463,7 @@
@reflectiveTest
class PubDependencyTest extends AbstractLinterContextTest {
test_dependencies() async {
- newFile('/test/pubspec.yaml', content: '''
+ newFile('$testPackageRootPath/pubspec.yaml', content: '''
name: test
dependencies:
diff --git a/pkg/analyzer/test/src/lint/linter/resolve_name_in_scope_test.dart b/pkg/analyzer/test/src/lint/linter/resolve_name_in_scope_test.dart
index 3aa45e2..8ad3449 100644
--- a/pkg/analyzer/test/src/lint/linter/resolve_name_in_scope_test.dart
+++ b/pkg/analyzer/test/src/lint/linter/resolve_name_in_scope_test.dart
@@ -48,7 +48,7 @@
}
test_class_getter_different_importScope() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
set foo(int _) {}
''');
await resolve('''
@@ -86,7 +86,7 @@
}
test_class_getter_requested_importScope() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
int get foo => 0;
''');
await resolve('''
@@ -246,7 +246,7 @@
}
test_class_method_requested_importScope() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
void foo() {}
''');
await resolve('''
@@ -490,7 +490,7 @@
}
test_class_setter_requested_importScope() async {
- newFile('/test/lib/a.dart', content: r'''
+ newFile('$testPackageLibPath/a.dart', content: r'''
set foo(int _) {}
''');
await resolve('''
diff --git a/pkg/analyzer/test/src/summary/element_text.dart b/pkg/analyzer/test/src/summary/element_text.dart
index 951af04..b630645 100644
--- a/pkg/analyzer/test/src/summary/element_text.dart
+++ b/pkg/analyzer/test/src/summary/element_text.dart
@@ -965,6 +965,7 @@
writeIf(e.isSynthetic, 'synthetic ');
writeIf(e.isStatic, 'static ');
+ writeIf(e is FieldElementImpl && e.isAbstract, 'abstract ');
writeIf(e is FieldElementImpl && e.isCovariant, 'covariant ');
} else {
writeDocumentation(e);
diff --git a/pkg/analyzer/test/src/summary/resolved_ast_printer.dart b/pkg/analyzer/test/src/summary/resolved_ast_printer.dart
index 20384ca..70960ee 100644
--- a/pkg/analyzer/test/src/summary/resolved_ast_printer.dart
+++ b/pkg/analyzer/test/src/summary/resolved_ast_printer.dart
@@ -497,6 +497,7 @@
_writeln('FieldDeclaration');
_withIndent(() {
var properties = _Properties();
+ properties.addToken('abstractKeyword', node.abstractKeyword);
properties.addToken('covariantKeyword', node.covariantKeyword);
properties.addNode('fields', node.fields);
properties.addToken('semicolon', node.semicolon);
diff --git a/pkg/analyzer/test/src/summary/resynthesize_common.dart b/pkg/analyzer/test/src/summary/resynthesize_common.dart
index ce8cd1c..5c26d58 100644
--- a/pkg/analyzer/test/src/summary/resynthesize_common.dart
+++ b/pkg/analyzer/test/src/summary/resynthesize_common.dart
@@ -6062,6 +6062,20 @@
''');
}
+ test_field_abstract() async {
+ featureSet = enableNnbd;
+ var library = await checkLibrary('''
+abstract class C {
+ abstract int i;
+}
+''');
+ checkElementText(library, '''
+abstract class C {
+ abstract int i;
+}
+''');
+ }
+
test_field_covariant() async {
var library = await checkLibrary('''
class C {
diff --git a/pkg/analyzer/test/src/summary/top_level_inference_test.dart b/pkg/analyzer/test/src/summary/top_level_inference_test.dart
index 0139c85..1d3f695 100644
--- a/pkg/analyzer/test/src/summary/top_level_inference_test.dart
+++ b/pkg/analyzer/test/src/summary/top_level_inference_test.dart
@@ -12,7 +12,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../dart/analysis/base.dart';
-import '../dart/resolution/driver_resolution.dart';
+import '../dart/resolution/context_collection_resolution.dart';
import 'element_text.dart';
main() {
@@ -32,7 +32,7 @@
}
@reflectiveTest
-class TopLevelInferenceErrorsTest extends DriverResolutionTest {
+class TopLevelInferenceErrorsTest extends PubPackageResolutionTest {
test_initializer_additive() async {
await _assertErrorOnlyLeft(['+', '-']);
}
diff --git a/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart b/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart
index cec16f8..c67500c 100644
--- a/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart
+++ b/pkg/analyzer/test/src/task/strong/dart2_inference_test.dart
@@ -11,7 +11,7 @@
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../dart/resolution/driver_resolution.dart';
+import '../../dart/resolution/context_collection_resolution.dart';
void main() {
defineReflectiveSuite(() {
@@ -23,7 +23,7 @@
///
/// https://github.com/dart-lang/sdk/issues/31638
@reflectiveTest
-class Dart2InferenceTest extends DriverResolutionTest {
+class Dart2InferenceTest extends PubPackageResolutionTest {
test_bool_assert() async {
var code = r'''
T f<T>(int _) => null;
diff --git a/pkg/analyzer/test/src/workspace/package_build_test.dart b/pkg/analyzer/test/src/workspace/package_build_test.dart
index 630bf0c..42c46c4 100644
--- a/pkg/analyzer/test/src/workspace/package_build_test.dart
+++ b/pkg/analyzer/test/src/workspace/package_build_test.dart
@@ -4,14 +4,12 @@
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/test_utilities/resource_provider_mixin.dart';
import 'package:analyzer/src/workspace/package_build.dart';
+import 'package:meta/meta.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
-import '../../generated/test_support.dart';
-
main() {
defineReflectiveSuite(() {
defineReflectiveTests(PackageBuildFileUriResolverTest);
@@ -49,7 +47,7 @@
void setUp() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
workspace = PackageBuildWorkspace.find(
resourceProvider,
@@ -137,7 +135,7 @@
}
void setUp() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
}
void test_resolveAbsolute_generated() {
@@ -228,98 +226,168 @@
@reflectiveTest
class PackageBuildWorkspacePackageTest with ResourceProviderMixin {
- MockUriResolver packageUriResolver;
+ PackageBuildWorkspace myWorkspace;
+ PackageBuildWorkspacePackage myPackage;
- void test_contains_differentWorkspace() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace2/project2/lib/file.dart');
+ String get fooPackageLibPath => '$fooPackageRootPath/lib';
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/lib/code.dart'));
- expect(
- package.contains(
- TestSource(convertPath('/workspace2/project2/lib/file.dart'))),
- isFalse);
+ String get fooPackageRootPath => '$myWorkspacePath/foo';
+
+ String get myPackageGeneratedPath {
+ return '$myPackageRootPath/.dart_tool/build/generated';
}
- void test_contains_packageUris() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/lib/file2.dart');
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/lib/code.dart'));
- var file2Source = InSummarySource(
- Uri.parse('package:project/file2.dart'), '' /* summaryPath */);
- expect(package.contains(file2Source), isTrue);
- }
+ String get myPackageLibPath => '$myPackageRootPath/lib';
- void test_contains_packageUris_unrelatedFile() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/lib/file2.dart');
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/lib/code.dart'));
- var file2Source = InSummarySource(
- Uri.parse('package:project2/file2.dart'), '' /* summaryPath */);
- expect(package.contains(file2Source), isFalse);
- }
+ String get myPackageRootPath => '$myWorkspacePath/my';
- void test_contains_sameWorkspace() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/lib/file2.dart');
+ String get myWorkspacePath => '/workspace';
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/lib/code.dart'));
- var file2Path = convertPath('/workspace/project/lib/file2.dart');
- expect(package.contains(TestSource(file2Path)), isTrue);
- var binPath = convertPath('/workspace/project/bin/bin.dart');
- expect(package.contains(TestSource(binPath)), isTrue);
- var testPath = convertPath('/workspace/project/test/test.dart');
- expect(package.contains(TestSource(testPath)), isTrue);
- }
+ void setUp() {
+ newFile('$myPackageRootPath/pubspec.yaml', content: 'name: my');
+ newFolder(myPackageGeneratedPath);
- void test_findPackageFor_includedFile() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/lib/file.dart');
-
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/lib/file.dart'));
- expect(package, isNotNull);
- expect(package.root, convertPath('/workspace'));
- expect(package.workspace, equals(workspace));
- }
-
- void test_findPackageFor_testFile() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/test/test.dart');
-
- var package = workspace
- .findPackageFor(convertPath('/workspace/project/test/test.dart'));
- expect(package, isNotNull);
- expect(package.root, convertPath('/workspace'));
- expect(package.workspace, equals(workspace));
- }
-
- void test_findPackageFor_unrelatedFile() {
- PackageBuildWorkspace workspace = _createPackageBuildWorkspace();
- newFile('/workspace/project/lib/file.dart');
-
- var package = workspace
- .findPackageFor(convertPath('/workspace2/project2/lib/file.dart'));
- expect(package, isNull);
- }
-
- PackageBuildWorkspace _createPackageBuildWorkspace() {
- newFolder('/workspace/.dart_tool/build');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
- PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
+ myWorkspace = PackageBuildWorkspace.find(
resourceProvider,
{
- 'project': [getFolder('/workspace')]
+ 'my': [getFolder(myPackageLibPath)],
+ 'foo': [getFolder(fooPackageLibPath)],
},
- convertPath('/workspace'),
+ convertPath(myPackageRootPath),
);
- packageUriResolver = MockUriResolver();
- PackageBuildPackageUriResolver(workspace, packageUriResolver);
- return workspace;
+
+ myPackage = myWorkspace.findPackageFor('$myPackageLibPath/fake.dart');
+ }
+
+ test_contains_fileUri() {
+ expect(
+ myPackage.contains(
+ _sourceWithFileUri('$myPackageRootPath/test/a.dart'),
+ ),
+ isTrue,
+ );
+
+ expect(
+ myPackage.contains(
+ _sourceWithFileUri('$fooPackageRootPath/test/a.dart'),
+ ),
+ isFalse,
+ );
+ }
+
+ test_contains_fileUri_generated() {
+ var myGeneratedPath = '$myPackageGeneratedPath/my/test/a.dart';
+ newFile(myGeneratedPath, content: '');
+
+ var fooGeneratedPath = '$myPackageGeneratedPath/foo/test/a.dart';
+ newFile(fooGeneratedPath, content: '');
+
+ expect(
+ myPackage.contains(
+ _sourceWithFileUri(myGeneratedPath),
+ ),
+ isTrue,
+ );
+
+ expect(
+ myPackage.contains(
+ _sourceWithFileUri(fooGeneratedPath),
+ ),
+ isFalse,
+ );
+ }
+
+ test_contains_packageUri() {
+ expect(
+ myPackage.contains(
+ _sourceWithPackageUriWithoutPath('package:my/a.dart'),
+ ),
+ isTrue,
+ );
+
+ expect(
+ myPackage.contains(
+ _sourceWithPackageUriWithoutPath('package:foo/a.dart'),
+ ),
+ isFalse,
+ );
+ }
+
+ test_findPackageFor_my_generated_libFile() {
+ var package = myWorkspace.findPackageFor(
+ convertPath('$myPackageGeneratedPath/my/lib/a.dart'),
+ );
+ expect(package, isNotNull);
+ expect(package.root, convertPath(myPackageRootPath));
+ expect(package.workspace, myWorkspace);
+ }
+
+ test_findPackageFor_my_generated_other() {
+ expect(
+ myWorkspace.findPackageFor(
+ convertPath('$myPackageGeneratedPath/foo/lib/a.dart'),
+ ),
+ isNull,
+ );
+
+ expect(
+ myWorkspace.findPackageFor(
+ convertPath('$myPackageGeneratedPath/foo/test/a.dart'),
+ ),
+ isNull,
+ );
+ }
+
+ test_findPackageFor_my_generated_testFile() {
+ var package = myWorkspace.findPackageFor(
+ convertPath('$myPackageGeneratedPath/my/test/a.dart'),
+ );
+ expect(package, isNotNull);
+ expect(package.root, convertPath(myPackageRootPath));
+ expect(package.workspace, myWorkspace);
+ }
+
+ test_findPackageFor_my_libFile() {
+ var package = myWorkspace.findPackageFor(
+ convertPath('$myPackageLibPath/a.dart'),
+ );
+ expect(package, isNotNull);
+ expect(package.root, convertPath(myPackageRootPath));
+ expect(package.workspace, myWorkspace);
+ }
+
+ test_findPackageFor_my_testFile() {
+ var package = myWorkspace.findPackageFor(
+ convertPath('$myPackageRootPath/test/a.dart'),
+ );
+ expect(package, isNotNull);
+ expect(package.root, convertPath(myPackageRootPath));
+ expect(package.workspace, myWorkspace);
+ }
+
+ test_findPackageFor_other() {
+ expect(
+ myWorkspace.findPackageFor(
+ convertPath('$fooPackageRootPath/lib/a.dart'),
+ ),
+ isNull,
+ );
+
+ expect(
+ myWorkspace.findPackageFor(
+ convertPath('$fooPackageRootPath/test/a.dart'),
+ ),
+ isNull,
+ );
+ }
+
+ Source _sourceWithFileUri(String path) {
+ return _MockSource(path: convertPath(path), uri: toUri(path));
+ }
+
+ Source _sourceWithPackageUriWithoutPath(String uriStr) {
+ var uri = Uri.parse(uriStr);
+ return _MockSource(path: null, uri: uri);
}
}
@@ -327,7 +395,7 @@
class PackageBuildWorkspaceTest with ResourceProviderMixin {
void test_builtFile_currentProject() {
newFolder('/workspace/.dart_tool/build');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -339,7 +407,7 @@
void test_builtFile_importedPackage() {
newFolder('/workspace/.dart_tool/build');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project', 'foo']);
@@ -350,7 +418,7 @@
void test_builtFile_notInPackagesGetsHidden() {
newFolder('/workspace/.dart_tool/build');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
// Ensure package:bar is not configured.
PackageBuildWorkspace workspace =
@@ -378,7 +446,7 @@
void test_find_hasDartToolAndPubspec() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -391,9 +459,9 @@
void test_find_hasDartToolAndPubspec_inParentDirectory() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
newFolder('/workspace/opened/up/a/child/dir/.dart_tool/build');
- newFileWithBytes('/workspace/opened/up/a/child/dir/pubspec.yaml',
- 'name: subproject'.codeUnits);
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/opened/up/a/child/dir/pubspec.yaml',
+ content: 'name: subproject');
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -407,9 +475,9 @@
test_find_hasDartToolAndPubspec_inParentDirectory_ignoresMalformedPubspec() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
newFolder('/workspace/opened/up/a/child/dir/.dart_tool/build');
- newFileWithBytes('/workspace/opened/up/a/child/dir/pubspec.yaml',
- 'not: yaml: here!!! 111'.codeUnits);
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/opened/up/a/child/dir/pubspec.yaml',
+ content: 'not: yaml: here!!! 111');
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -423,7 +491,7 @@
newFolder('/workspace/.dart_tool/build/generated/project/lib');
newFolder('/workspace/opened/up/a/child/dir');
newFolder('/workspace/opened/up/a/child/dir/.dart_tool/build');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -436,9 +504,9 @@
void test_find_hasDartToolAndPubspec_inParentDirectory_ignoresSoloPubspec() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
newFolder('/workspace/opened/up/a/child/dir');
- newFileWithBytes('/workspace/opened/up/a/child/dir/pubspec.yaml',
- 'name: subproject'.codeUnits);
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/opened/up/a/child/dir/pubspec.yaml',
+ content: 'name: subproject');
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -451,7 +519,7 @@
void test_find_hasDartToolNoBuild() {
// Edge case: an empty .dart_tool directory. Don't assume package:build.
newFolder('/workspace/.dart_tool');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -473,7 +541,7 @@
void test_find_hasDartToolPubButNotBuild() {
// Dart projects will have this directory, that don't use package:build.
newFolder('/workspace/.dart_tool/pub');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -484,8 +552,7 @@
void test_find_hasMalformedPubspec() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes(
- '/workspace/pubspec.yaml', 'not: yaml: here! 1111'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'not: yaml: here! 1111');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -495,7 +562,7 @@
}
void test_find_hasPubspecNoDartTool() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace = PackageBuildWorkspace.find(
resourceProvider,
{},
@@ -506,7 +573,7 @@
void test_findFile_bin() {
newFolder('/workspace/.dart_tool/build/generated/project/bin');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -517,7 +584,7 @@
void test_findFile_binGenerated() {
newFolder('/workspace/.dart_tool/build/generated/project/bin');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -529,7 +596,7 @@
void test_findFile_libGenerated() {
newFolder('/workspace/.dart_tool/build/generated/project/lib');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -541,7 +608,7 @@
void test_findFile_test() {
newFolder('/workspace/.dart_tool/build/generated/project/test');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -552,7 +619,7 @@
void test_findFile_testGenerated() {
newFolder('/workspace/.dart_tool/build/generated/project/test');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -564,7 +631,7 @@
void test_findFile_web() {
newFolder('/workspace/.dart_tool/build/generated/project/web');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -575,7 +642,7 @@
void test_findFile_webGenerated() {
newFolder('/workspace/.dart_tool/build/generated/project/web');
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PackageBuildWorkspace workspace =
_createWorkspace('/workspace', ['project']);
@@ -599,3 +666,24 @@
);
}
}
+
+class _MockSource implements Source {
+ final String path;
+
+ @override
+ final Uri uri;
+
+ _MockSource({@required this.path, @required this.uri});
+
+ @override
+ String get fullName {
+ if (path == null) {
+ throw StateError('This source has no path, '
+ 'and we do not expect that it will be accessed.');
+ }
+ return path;
+ }
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
diff --git a/pkg/analyzer/test/src/workspace/pub_test.dart b/pkg/analyzer/test/src/workspace/pub_test.dart
index c5d5c3c..a33908a 100644
--- a/pkg/analyzer/test/src/workspace/pub_test.dart
+++ b/pkg/analyzer/test/src/workspace/pub_test.dart
@@ -21,7 +21,7 @@
PubWorkspace workspace;
setUp() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
workspace =
PubWorkspace.find(resourceProvider, {}, convertPath('/workspace'));
expect(workspace.isBazel, isFalse);
@@ -79,7 +79,7 @@
@reflectiveTest
class PubWorkspaceTest with ResourceProviderMixin {
void test_find_directory() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PubWorkspace workspace =
PubWorkspace.find(resourceProvider, {}, convertPath('/workspace'));
expect(workspace.isBazel, isFalse);
@@ -94,7 +94,7 @@
}
void test_find_file() {
- newFileWithBytes('/workspace/pubspec.yaml', 'name: project'.codeUnits);
+ newFile('/workspace/pubspec.yaml', content: 'name: project');
PubWorkspace workspace = PubWorkspace.find(
resourceProvider, {}, convertPath('/workspace/lib/lib1.dart'));
expect(workspace.root, convertPath('/workspace'));
diff --git a/pkg/analyzer/test/verify_diagnostics_test.dart b/pkg/analyzer/test/verify_diagnostics_test.dart
index 745e237..78e3e14 100644
--- a/pkg/analyzer/test/verify_diagnostics_test.dart
+++ b/pkg/analyzer/test/verify_diagnostics_test.dart
@@ -3,22 +3,18 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:analyzer/dart/analysis/analysis_context_collection.dart';
-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/error/error.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/test_utilities/package_mixin.dart';
import 'package:path/path.dart';
-import 'package:pub_semver/src/version_constraint.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../tool/diagnostics/generate.dart';
-import 'src/dart/resolution/driver_resolution.dart';
+import 'src/dart/resolution/context_collection_resolution.dart';
main() {
defineReflectiveSuite(() {
@@ -399,51 +395,48 @@
/// A test class that creates an environment suitable for analyzing the
/// snippets.
-class _SnippetTest extends DriverResolutionTest with PackageMixin {
+class _SnippetTest extends PubPackageResolutionTest {
/// The snippet being tested.
final _SnippetData snippet;
- @override
- AnalysisOptionsImpl analysisOptions = AnalysisOptionsImpl();
-
/// Initialize a newly created test to test the given [snippet].
_SnippetTest(this.snippet) {
- analysisOptions.contextFeatures =
- FeatureSet.fromEnableFlags(snippet.experiments ?? []);
- String pubspecContent = snippet.auxiliaryFiles['pubspec.yaml'];
- if (pubspecContent != null) {
- for (String line in pubspecContent.split('\n')) {
- if (line.indexOf('sdk:') > 0) {
- int start = line.indexOf("'") + 1;
- String constraint = line.substring(start, line.indexOf("'", start));
- analysisOptions.sdkVersionConstraint =
- VersionConstraint.parse(constraint);
- }
- }
- }
+ writeTestPackageAnalysisOptionsFile(
+ AnalysisOptionsFileConfig(
+ experiments: snippet.experiments,
+ ),
+ );
}
@override
void setUp() {
super.setUp();
- addMetaPackage();
_createAuxiliaryFiles(snippet.auxiliaryFiles);
addTestFile(snippet.content);
}
void _createAuxiliaryFiles(Map<String, String> auxiliaryFiles) {
- Map<String, String> packageMap = {};
- for (String uri in auxiliaryFiles.keys) {
- if (uri.startsWith('package:')) {
- int slash = uri.indexOf('/');
- String packageName = uri.substring(8, slash);
- String libPath = packageMap.putIfAbsent(
- packageName, () => addPubPackage(packageName).path);
- String relativePath = uri.substring(slash + 1);
- newFile('$libPath/$relativePath', content: auxiliaryFiles[uri]);
+ Map<String, String> packageNameToRootPath = {};
+ for (String uriStr in auxiliaryFiles.keys) {
+ if (uriStr.startsWith('package:')) {
+ Uri uri = Uri.parse(uriStr);
+
+ String packageName = uri.pathSegments[0];
+ String packageRootPath = '/packages/$packageName';
+ packageNameToRootPath[packageName] = convertPath(packageRootPath);
+
+ String pathInLib = uri.pathSegments.skip(1).join('/');
+ newFile(
+ '$packageRootPath/lib/$pathInLib',
+ content: auxiliaryFiles[uriStr],
+ );
} else {
- newFile('/test/$uri', content: auxiliaryFiles[uri]);
+ newFile(
+ '$testPackageRootPath/$uriStr',
+ content: auxiliaryFiles[uriStr],
+ );
}
}
+ writeTestPackageConfigWith(packageNameToRootPath, meta: true);
}
}
diff --git a/pkg/compiler/lib/src/commandline_options.dart b/pkg/compiler/lib/src/commandline_options.dart
index 9e116f8..aea3bac 100644
--- a/pkg/compiler/lib/src/commandline_options.dart
+++ b/pkg/compiler/lib/src/commandline_options.dart
@@ -29,6 +29,7 @@
static const String experimentalAllocationsPath =
'--experimental-allocations-path';
+ static const String experimentalWrapped = '--experimental-wrapped';
static const String experimentalPowersets = '--experimental-powersets';
// Temporary experiment for code generation of locals for frequently used
@@ -107,6 +108,8 @@
static const String newDeferredSplit = '--new-deferred-split';
static const String reportInvalidInferredDeferredTypes =
'--report-invalid-deferred-types';
+ static const String deferClassTypes = '--defer-class-types';
+ static const String noDeferClassTypes = '--no-defer-class-types';
/// Flag for a combination of flags for 'production' mode.
static const String benchmarkingProduction = '--benchmarking-production';
@@ -155,6 +158,9 @@
'${Flags.enableLanguageExperiments}|'
'${Flags.enableLanguageExperiments}=.*';
+ static const String multiRoots = '--multi-root=.+';
+ static const String multiRootScheme = '--multi-root-scheme=.+';
+
// Experimental options.
static const String resolutionInput = '--resolution-input=.+';
static const String bazelPaths = '--bazel-paths=.+';
diff --git a/pkg/compiler/lib/src/common_elements.dart b/pkg/compiler/lib/src/common_elements.dart
index dfcea46..48db7fd 100644
--- a/pkg/compiler/lib/src/common_elements.dart
+++ b/pkg/compiler/lib/src/common_elements.dart
@@ -2283,6 +2283,15 @@
/// Calls [f] for each supertype of [cls].
void forEachSupertype(ClassEntity cls, void f(InterfaceType supertype));
+ /// Calls [f] for each SuperClass of [cls].
+ void forEachSuperClass(ClassEntity cls, void f(ClassEntity superClass)) {
+ for (var superClass = getSuperClass(cls);
+ superClass != null;
+ superClass = getSuperClass(superClass)) {
+ f(superClass);
+ }
+ }
+
/// Create the instantiation of [cls] with the given [typeArguments] and
/// [nullability].
InterfaceType createInterfaceType(
@@ -2336,6 +2345,23 @@
/// Returns `true` if [cls] is a Dart enum class.
bool isEnumClass(ClassEntity cls);
+
+ /// Returns the 'effective' mixin class if [cls] is a mixin application, and
+ /// `null` otherwise.
+ ///
+ /// The 'effective' mixin class is the class from which members are mixed in.
+ /// Normally this is the mixin class itself, but not if the mixin class itself
+ /// is a mixin application.
+ ///
+ /// Consider this hierarchy:
+ ///
+ /// class A {}
+ /// class B = Object with A {}
+ /// class C = Object with B {}
+ ///
+ /// The mixin classes of `B` and `C` are `A` and `B`, respectively, but the
+ /// _effective_ mixin class of both is `A`.
+ ClassEntity getEffectiveMixinClass(ClassEntity cls);
}
abstract class KElementEnvironment extends ElementEnvironment {
@@ -2377,23 +2403,6 @@
/// super calls.
bool isSuperMixinApplication(ClassEntity cls);
- /// Returns the 'effective' mixin class if [cls] is a mixin application, and
- /// `null` otherwise.
- ///
- /// The 'effective' mixin class is the class from which members are mixed in.
- /// Normally this is the mixin class itself, but not if the mixin class itself
- /// is a mixin application.
- ///
- /// Consider this hierarchy:
- ///
- /// class A {}
- /// class B = Object with A {}
- /// class C = Object with B {}
- ///
- /// The mixin classes of `B` and `C` are `A` and `B`, respectively, but the
- /// _effective_ mixin class of both is `A`.
- ClassEntity getEffectiveMixinClass(ClassEntity cls);
-
/// The default type of the [typeVariable].
///
/// This is the type used as the default type argument when no explicit type
diff --git a/pkg/compiler/lib/src/compiler.dart b/pkg/compiler/lib/src/compiler.dart
index 54828f1..62d62d5 100644
--- a/pkg/compiler/lib/src/compiler.dart
+++ b/pkg/compiler/lib/src/compiler.dart
@@ -29,6 +29,7 @@
import 'inferrer/abstract_value_domain.dart' show AbstractValueStrategy;
import 'inferrer/trivial.dart' show TrivialAbstractValueStrategy;
import 'inferrer/powersets/wrapped.dart' show WrappedAbstractValueStrategy;
+import 'inferrer/powersets/powersets.dart' show PowersetStrategy;
import 'inferrer/typemasks/masks.dart' show TypeMaskStrategy;
import 'inferrer/types.dart'
show GlobalTypeInferenceResults, GlobalTypeInferenceTask;
@@ -139,9 +140,11 @@
abstractValueStrategy = options.useTrivialAbstractValueDomain
? const TrivialAbstractValueStrategy()
: const TypeMaskStrategy();
- if (options.experimentalPowersets) {
+ if (options.experimentalWrapped) {
abstractValueStrategy =
WrappedAbstractValueStrategy(abstractValueStrategy);
+ } else if (options.experimentalPowersets) {
+ abstractValueStrategy = PowersetStrategy(abstractValueStrategy);
}
CompilerTask kernelFrontEndTask;
diff --git a/pkg/compiler/lib/src/dart2js.dart b/pkg/compiler/lib/src/dart2js.dart
index 32c3b63..4022219 100644
--- a/pkg/compiler/lib/src/dart2js.dart
+++ b/pkg/compiler/lib/src/dart2js.dart
@@ -112,6 +112,8 @@
int codegenShard;
int codegenShards;
List<String> bazelPaths;
+ List<String> multiRoots;
+ String multiRootScheme = 'org-dartlang-app';
Uri packageConfig = null;
List<String> options = new List<String>();
bool wantHelp = false;
@@ -196,6 +198,16 @@
bazelPaths = <String>[]..addAll(paths.split(','));
}
+ void setMultiRoots(String argument) {
+ String paths = extractParameter(argument);
+ multiRoots ??= <String>[];
+ multiRoots.addAll(paths.split(','));
+ }
+
+ void setMultiRootScheme(String argument) {
+ multiRootScheme = extractParameter(argument);
+ }
+
String getDepsOutput(Iterable<Uri> sourceFiles) {
var filenames = sourceFiles.map((uri) => '$uri').toList();
filenames.sort();
@@ -438,6 +450,8 @@
new OptionHandler(Flags.noSourceMaps, passThrough),
new OptionHandler(Option.resolutionInput, ignoreOption),
new OptionHandler(Option.bazelPaths, setBazelPaths),
+ new OptionHandler(Option.multiRoots, setMultiRoots),
+ new OptionHandler(Option.multiRootScheme, setMultiRootScheme),
new OptionHandler(Flags.resolveOnly, ignoreOption),
new OptionHandler(Flags.disableNativeLiveTypeAnalysis, passThrough),
new OptionHandler('--categories=.*', setCategories),
@@ -446,12 +460,15 @@
new OptionHandler(Flags.disableProgramSplit, passThrough),
new OptionHandler(Flags.disableTypeInference, passThrough),
new OptionHandler(Flags.useTrivialAbstractValueDomain, passThrough),
+ new OptionHandler(Flags.experimentalWrapped, passThrough),
new OptionHandler(Flags.experimentalPowersets, passThrough),
new OptionHandler(Flags.disableRtiOptimization, passThrough),
new OptionHandler(Flags.terse, passThrough),
new OptionHandler('--deferred-map=.+', passThrough),
new OptionHandler(Flags.newDeferredSplit, passThrough),
new OptionHandler(Flags.reportInvalidInferredDeferredTypes, passThrough),
+ new OptionHandler(Flags.deferClassTypes, passThrough),
+ new OptionHandler(Flags.noDeferClassTypes, passThrough),
new OptionHandler('${Flags.dumpInfo}|${Flags.dumpInfo}=.+', setDumpInfo),
new OptionHandler('--disallow-unsafe-eval', ignoreOption),
new OptionHandler(Option.showPackageWarnings, passThrough),
@@ -515,7 +532,14 @@
// TODO(johnniwinther): Measure time for reading files.
SourceFileProvider inputProvider;
if (bazelPaths != null) {
+ if (multiRoots != null) {
+ helpAndFail(
+ 'The options --bazel-root and --multi-root cannot be supplied '
+ 'together, please choose one or the other.');
+ }
inputProvider = new BazelInputProvider(bazelPaths);
+ } else if (multiRoots != null) {
+ inputProvider = new MultiRootInputProvider(multiRootScheme, multiRoots);
} else {
inputProvider = new CompilerSourceFileProvider();
}
diff --git a/pkg/compiler/lib/src/deferred_load.dart b/pkg/compiler/lib/src/deferred_load.dart
index 97c7256..1db440d 100644
--- a/pkg/compiler/lib/src/deferred_load.dart
+++ b/pkg/compiler/lib/src/deferred_load.dart
@@ -110,6 +110,9 @@
/// A mapping from classes to their import set.
Map<ClassEntity, ImportSet> _classToSet = {};
+ /// A mapping from interface types (keyed by classes) to their import set.
+ Map<ClassEntity, ImportSet> _classTypeToSet = {};
+
/// A mapping from members to their import set.
Map<MemberEntity, ImportSet> _memberToSet = {};
@@ -135,6 +138,7 @@
bool get newDeferredSplit => compiler.options.newDeferredSplit;
bool get reportInvalidInferredDeferredTypes =>
compiler.options.reportInvalidInferredDeferredTypes;
+ bool get deferClassTypes => compiler.options.deferClassTypes;
DeferredLoadTask(this.compiler) : super(compiler.measurer) {
_mainOutputUnit = OutputUnit(true, 'main', <ImportEntity>{});
@@ -204,12 +208,24 @@
_collectDirectMemberDependencies(closedWorld, member, dependencies);
}
+ void addClassAndMaybeAddEffectiveMixinClass(ClassEntity cls) {
+ dependencies.addClass(cls);
+ if (elementEnvironment.isMixinApplication(cls)) {
+ dependencies.addClass(elementEnvironment.getEffectiveMixinClass(cls));
+ }
+ }
+
ClassEntity cls = element;
elementEnvironment.forEachLocalClassMember(cls, addLiveInstanceMember);
elementEnvironment.forEachSupertype(cls, (InterfaceType type) {
_collectTypeDependencies(type, dependencies);
});
- dependencies.addClass(cls);
+ elementEnvironment.forEachSuperClass(cls, (superClass) {
+ addClassAndMaybeAddEffectiveMixinClass(superClass);
+ _collectTypeDependencies(
+ elementEnvironment.getThisType(superClass), dependencies);
+ });
+ addClassAndMaybeAddEffectiveMixinClass(cls);
}
/// Finds all elements and constants that [element] depends directly on.
@@ -254,14 +270,17 @@
/// Recursively collects all the dependencies of [type].
void _collectTypeDependencies(DartType type, Dependencies dependencies,
[ImportEntity import]) {
- TypeDependencyVisitor(dependencies, import, commonElements).visit(type);
+ TypeDependencyVisitor(dependencies, import, commonElements,
+ collectClassesAndTypes: !deferClassTypes)
+ .visit(type);
}
void _collectTypeArgumentDependencies(
Iterable<DartType> typeArguments, Dependencies dependencies,
[ImportEntity import]) {
if (typeArguments == null) return;
- TypeDependencyVisitor(dependencies, import, commonElements)
+ TypeDependencyVisitor(dependencies, import, commonElements,
+ collectClassesAndTypes: !deferClassTypes)
.visitList(typeArguments);
}
@@ -309,21 +328,29 @@
default:
}
}, visitTypeUse: (MemberEntity member, TypeUse typeUse) {
+ void addClassIfInterfaceType(DartType t, [ImportEntity import]) {
+ var typeWithoutNullability = t.withoutNullability;
+ if (typeWithoutNullability is InterfaceType) {
+ dependencies.addClass(typeWithoutNullability.element, import);
+ }
+ }
+
DartType type = typeUse.type;
switch (typeUse.kind) {
case TypeUseKind.TYPE_LITERAL:
- var typeWithoutNullability = type.withoutNullability;
- if (typeWithoutNullability is InterfaceType) {
- dependencies.addClass(
- typeWithoutNullability.element, typeUse.deferredImport);
- }
+ _collectTypeDependencies(
+ type, dependencies, typeUse.deferredImport);
break;
case TypeUseKind.CONST_INSTANTIATION:
+ addClassIfInterfaceType(type, typeUse.deferredImport);
_collectTypeDependencies(
type, dependencies, typeUse.deferredImport);
break;
case TypeUseKind.INSTANTIATION:
case TypeUseKind.NATIVE_INSTANTIATION:
+ addClassIfInterfaceType(type);
+ _collectTypeDependencies(type, dependencies);
+ break;
case TypeUseKind.IS_CHECK:
case TypeUseKind.CATCH_TYPE:
_collectTypeDependencies(type, dependencies);
@@ -447,6 +474,33 @@
}
}
+ void _updateClassTypeRecursive(KClosedWorld closedWorld, ClassEntity element,
+ ImportSet oldSet, ImportSet newSet, WorkQueue queue) {
+ if (element == null) return;
+
+ ImportSet currentSet = _classTypeToSet[element];
+
+ // Already visited. We may visit some root nodes a second time with
+ // [isMirrorUsage] in order to mark static members used reflectively.
+ if (currentSet == newSet) return;
+
+ // Elements in the main output unit always remain there.
+ if (currentSet == importSets.mainSet) return;
+
+ if (currentSet == oldSet) {
+ // Continue recursively updating from [oldSet] to [newSet].
+ _classTypeToSet[element] = newSet;
+
+ Dependencies dependencies = Dependencies();
+ dependencies.addClassType(element);
+ LibraryEntity library = element.library;
+ _processDependencies(
+ closedWorld, library, dependencies, oldSet, newSet, queue, element);
+ } else {
+ queue.addClassType(element, newSet);
+ }
+ }
+
void _updateMemberRecursive(KClosedWorld closedWorld, MemberEntity element,
ImportSet oldSet, ImportSet newSet, WorkQueue queue) {
if (element == null) return;
@@ -579,6 +633,19 @@
}
});
+ dependencies.classType.forEach((ClassEntity cls, DependencyInfo info) {
+ _fixClassDependencyInfo(info, cls, library, context);
+ if (info.isDeferred) {
+ if (_shouldAddDeferredDependency(newSet)) {
+ for (ImportEntity deferredImport in info.imports) {
+ queue.addClassType(cls, importSets.singleton(deferredImport));
+ }
+ }
+ } else {
+ _updateClassTypeRecursive(closedWorld, cls, oldSet, newSet, queue);
+ }
+ });
+
dependencies.members.forEach((MemberEntity member, DependencyInfo info) {
_fixMemberDependencyInfo(info, member, library, context);
if (info.isDeferred) {
@@ -626,6 +693,7 @@
// Generate an output unit for all import sets that are associated with an
// element or constant.
_classToSet.values.forEach(addUnit);
+ _classTypeToSet.values.forEach(addUnit);
_memberToSet.values.forEach(addUnit);
_localFunctionToSet.values.forEach(addUnit);
_constantToSet.values.forEach(addUnit);
@@ -814,16 +882,19 @@
_createOutputUnits();
Map<String, List<OutputUnit>> hunksToLoad = _setupHunksToLoad();
Map<ClassEntity, OutputUnit> classMap = {};
+ Map<ClassEntity, OutputUnit> classTypeMap = {};
Map<MemberEntity, OutputUnit> memberMap = {};
Map<Local, OutputUnit> localFunctionMap = {};
Map<ConstantValue, OutputUnit> constantMap = {};
_classToSet.forEach((cls, s) => classMap[cls] = s.unit);
+ _classTypeToSet.forEach((cls, s) => classTypeMap[cls] = s.unit);
_memberToSet.forEach((member, s) => memberMap[member] = s.unit);
_localFunctionToSet.forEach(
(localFunction, s) => localFunctionMap[localFunction] = s.unit);
_constantToSet.forEach((constant, s) => constantMap[constant] = s.unit);
_classToSet = null;
+ _classTypeToSet = null;
_memberToSet = null;
_localFunctionToSet = null;
_constantToSet = null;
@@ -831,8 +902,10 @@
cleanup();
return OutputUnitData(
this.isProgramSplit && !disableProgramSplit,
+ deferClassTypes,
this._mainOutputUnit,
classMap,
+ classTypeMap,
memberMap,
localFunctionMap,
constantMap,
@@ -883,6 +956,13 @@
id = '$id cls';
elements.add(id);
});
+ _classTypeToSet.forEach((ClassEntity element, ImportSet importSet) {
+ if (ignoreEntityInDump(element)) return;
+ var elements = elementMap.putIfAbsent(importSet.unit, () => <String>[]);
+ var id = element.name ?? '$element';
+ id = '$id type';
+ elements.add(id);
+ });
_memberToSet.forEach((MemberEntity element, ImportSet importSet) {
if (ignoreEntityInDump(element)) return;
var elements = elementMap.putIfAbsent(importSet.unit, () => <String>[]);
@@ -1137,6 +1217,10 @@
/// An index to find work items in the queue corresponding to a class.
final Map<ClassEntity, WorkItem> pendingClasses = {};
+ /// An index to find work items in the queue corresponding to an
+ /// [InterfaceType] represented here by its [ClassEntitiy].
+ final Map<ClassEntity, WorkItem> pendingClassType = {};
+
/// An index to find work items in the queue corresponding to a member.
final Map<MemberEntity, WorkItem> pendingMembers = {};
@@ -1172,6 +1256,22 @@
}
}
+ /// Add to the queue that class type (represented by [element]) should be
+ /// updated to include all imports in [importSet]. If there is already a
+ /// work item in the queue for [element], this makes sure that the work
+ /// item now includes the union of [importSet] and the existing work
+ /// item's import set.
+ void addClassType(ClassEntity element, ImportSet importSet) {
+ var item = pendingClassType[element];
+ if (item == null) {
+ item = ClassTypeWorkItem(element, importSet);
+ pendingClassType[element] = item;
+ queue.add(item);
+ } else {
+ item.importsToAdd = _importSets.union(item.importsToAdd, importSet);
+ }
+ }
+
/// Add to the queue that [element] should be updated to include all imports
/// in [importSet]. If there is already a work item in the queue for
/// [element], this makes sure that the work item now includes the union of
@@ -1235,6 +1335,23 @@
}
}
+/// Summary of the work that needs to be done on a class.
+class ClassTypeWorkItem extends WorkItem {
+ /// Class to be recursively updated.
+ final ClassEntity cls;
+
+ ClassTypeWorkItem(this.cls, ImportSet newSet) : super(newSet);
+
+ @override
+ void update(
+ DeferredLoadTask task, KClosedWorld closedWorld, WorkQueue queue) {
+ queue.pendingClassType.remove(cls);
+ ImportSet oldSet = task._classTypeToSet[cls];
+ ImportSet newSet = task.importSets.union(oldSet, importsToAdd);
+ task._updateClassTypeRecursive(closedWorld, cls, oldSet, newSet, queue);
+ }
+}
+
/// Summary of the work that needs to be done on a member.
class MemberWorkItem extends WorkItem {
/// Member to be recursively updated.
@@ -1298,8 +1415,10 @@
static const String tag = 'output-unit-data';
final bool isProgramSplit;
+ final bool deferClassTypes;
final OutputUnit mainOutputUnit;
final Map<ClassEntity, OutputUnit> _classToUnit;
+ final Map<ClassEntity, OutputUnit> _classTypeToUnit;
final Map<MemberEntity, OutputUnit> _memberToUnit;
final Map<Local, OutputUnit> _localFunctionToUnit;
final Map<ConstantValue, OutputUnit> _constantToUnit;
@@ -1321,8 +1440,10 @@
OutputUnitData(
this.isProgramSplit,
+ this.deferClassTypes,
this.mainOutputUnit,
this._classToUnit,
+ this._classTypeToUnit,
this._memberToUnit,
this._localFunctionToUnit,
this._constantToUnit,
@@ -1345,6 +1466,8 @@
convertConstantMap) {
Map<ClassEntity, OutputUnit> classToUnit =
convertClassMap(other._classToUnit, other._localFunctionToUnit);
+ Map<ClassEntity, OutputUnit> classTypeToUnit =
+ convertClassMap(other._classTypeToUnit, other._localFunctionToUnit);
Map<MemberEntity, OutputUnit> memberToUnit =
convertMemberMap(other._memberToUnit, other._localFunctionToUnit);
Map<ConstantValue, OutputUnit> constantToUnit =
@@ -1360,8 +1483,10 @@
return OutputUnitData(
other.isProgramSplit,
+ other.deferClassTypes,
other.mainOutputUnit,
classToUnit,
+ classTypeToUnit,
memberToUnit,
// Local functions only make sense in the K-world model.
const <Local, OutputUnit>{},
@@ -1376,6 +1501,7 @@
factory OutputUnitData.readFromDataSource(DataSource source) {
source.begin(tag);
bool isProgramSplit = source.readBool();
+ bool deferClassTypes = source.readBool();
List<OutputUnit> outputUnits = source.readList(() {
bool isMainOutput = source.readBool();
String name = source.readString();
@@ -1387,6 +1513,9 @@
Map<ClassEntity, OutputUnit> classToUnit = source.readClassMap(() {
return outputUnits[source.readInt()];
});
+ Map<ClassEntity, OutputUnit> classTypeToUnit = source.readClassMap(() {
+ return outputUnits[source.readInt()];
+ });
Map<MemberEntity, OutputUnit> memberToUnit =
source.readMemberMap((MemberEntity member) {
return outputUnits[source.readInt()];
@@ -1411,8 +1540,10 @@
source.end(tag);
return OutputUnitData(
isProgramSplit,
+ deferClassTypes,
mainOutputUnit,
classToUnit,
+ classTypeToUnit,
memberToUnit,
// Local functions only make sense in the K-world model.
const <Local, OutputUnit>{},
@@ -1427,6 +1558,7 @@
void writeToDataSink(DataSink sink) {
sink.begin(tag);
sink.writeBool(isProgramSplit);
+ sink.writeBool(deferClassTypes);
Map<OutputUnit, int> outputUnitIndices = {};
sink.writeList(outputUnits, (OutputUnit outputUnit) {
outputUnitIndices[outputUnit] = outputUnitIndices.length;
@@ -1438,6 +1570,9 @@
sink.writeClassMap(_classToUnit, (OutputUnit outputUnit) {
sink.writeInt(outputUnitIndices[outputUnit]);
});
+ sink.writeClassMap(_classTypeToUnit, (OutputUnit outputUnit) {
+ sink.writeInt(outputUnitIndices[outputUnit]);
+ });
sink.writeMemberMap(_memberToUnit,
(MemberEntity member, OutputUnit outputUnit) {
sink.writeInt(outputUnitIndices[outputUnit]);
@@ -1473,6 +1608,23 @@
OutputUnit outputUnitForClassForTesting(ClassEntity cls) => _classToUnit[cls];
+ /// Returns the [OutputUnit] where [cls]'s type belongs.
+ // TODO(joshualitt): see above TODO regarding allowNull.
+ OutputUnit outputUnitForClassType(ClassEntity cls, {bool allowNull: false}) {
+ if (!isProgramSplit) return mainOutputUnit;
+ OutputUnit unit;
+ if (deferClassTypes) {
+ unit = _classTypeToUnit[cls];
+ } else {
+ unit = _classToUnit[cls];
+ }
+ assert(allowNull || unit != null, 'No output unit for type $cls');
+ return unit ?? mainOutputUnit;
+ }
+
+ OutputUnit outputUnitForClassTypeForTesting(ClassEntity cls) =>
+ deferClassTypes ? _classTypeToUnit[cls] : _classToUnit[cls];
+
/// Returns the [OutputUnit] where [member] belongs.
OutputUnit outputUnitForMember(MemberEntity member) {
if (!isProgramSplit) return mainOutputUnit;
@@ -1630,12 +1782,21 @@
class Dependencies {
final Map<ClassEntity, DependencyInfo> classes = {};
+ final Map<ClassEntity, DependencyInfo> classType = {};
final Map<MemberEntity, DependencyInfo> members = {};
final Set<Local> localFunctions = {};
final Map<ConstantValue, DependencyInfo> constants = {};
void addClass(ClassEntity cls, [ImportEntity import]) {
(classes[cls] ??= DependencyInfo()).registerImport(import);
+
+ // Add a classType dependency as well just in case we optimize out
+ // the class later.
+ addClassType(cls, import);
+ }
+
+ void addClassType(ClassEntity cls, [ImportEntity import]) {
+ (classType[cls] ??= DependencyInfo()).registerImport(import);
}
void addMember(MemberEntity m, [ImportEntity import]) {
@@ -1664,11 +1825,16 @@
}
class TypeDependencyVisitor implements DartTypeVisitor<void, Null> {
+ // If true, collect classes and types, otherwise just collect types.
+ // Note: When collecting classes, types are added implicitly by the
+ // dependencies class.
+ final bool collectClassesAndTypes;
final Dependencies _dependencies;
final ImportEntity _import;
final CommonElements _commonElements;
- TypeDependencyVisitor(this._dependencies, this._import, this._commonElements);
+ TypeDependencyVisitor(this._dependencies, this._import, this._commonElements,
+ {this.collectClassesAndTypes});
@override
void visit(DartType type, [_]) {
@@ -1691,7 +1857,11 @@
@override
void visitFutureOrType(FutureOrType type, Null argument) {
- _dependencies.addClass(_commonElements.futureClass);
+ if (collectClassesAndTypes) {
+ _dependencies.addClass(_commonElements.futureClass);
+ } else {
+ _dependencies.addClassType(_commonElements.futureClass);
+ }
visit(type.typeArgument);
}
@@ -1718,10 +1888,11 @@
@override
void visitInterfaceType(InterfaceType type, Null argument) {
visitList(type.typeArguments);
- // TODO(sigmund): when we are able to split classes from types in our
- // runtime-type representation, this should track type.element as a type
- // dependency instead.
- _dependencies.addClass(type.element, _import);
+ if (collectClassesAndTypes) {
+ _dependencies.addClass(type.element, _import);
+ } else {
+ _dependencies.addClassType(type.element, _import);
+ }
}
@override
diff --git a/pkg/compiler/lib/src/diagnostics/messages.dart b/pkg/compiler/lib/src/diagnostics/messages.dart
index e148654..4b78a07 100644
--- a/pkg/compiler/lib/src/diagnostics/messages.dart
+++ b/pkg/compiler/lib/src/diagnostics/messages.dart
@@ -77,7 +77,6 @@
JS_INTEROP_CLASS_NON_EXTERNAL_MEMBER,
JS_INTEROP_FIELD_NOT_SUPPORTED,
JS_INTEROP_NON_EXTERNAL_MEMBER,
- JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS,
JS_INTEROP_METHOD_WITH_NAMED_ARGUMENTS,
JS_OBJECT_LITERAL_CONSTRUCTOR_WITH_POSITIONAL_ARGUMENTS,
JS_PLACEHOLDER_CAPTURE,
@@ -201,12 +200,6 @@
MessageKind.JS_INTEROP_NON_EXTERNAL_MEMBER,
"Js-interop members must be 'external'."),
- MessageKind.JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS: const MessageTemplate(
- MessageKind.JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS,
- "Js-interop class members are only supported in js-interop classes.",
- howToFix: "Try marking the enclosing class as js-interop or "
- "remove the js-interop annotation from the member."),
-
MessageKind.JS_INTEROP_CLASS_NON_EXTERNAL_MEMBER: const MessageTemplate(
MessageKind.JS_INTEROP_CLASS_NON_EXTERNAL_MEMBER,
"Member '#{member}' in js-interop class '#{cls}' is not external.",
diff --git a/pkg/compiler/lib/src/inferrer/powersets/powersets.dart b/pkg/compiler/lib/src/inferrer/powersets/powersets.dart
new file mode 100644
index 0000000..60f9253
--- /dev/null
+++ b/pkg/compiler/lib/src/inferrer/powersets/powersets.dart
@@ -0,0 +1,722 @@
+// Copyright (c) 2018, 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 '../../constants/values.dart' show ConstantValue, PrimitiveConstantValue;
+import '../../elements/entities.dart';
+import '../../elements/names.dart';
+import '../../elements/types.dart' show DartType;
+import '../../ir/static_type.dart';
+import '../../serialization/serialization.dart';
+import '../../universe/selector.dart';
+import '../../universe/world_builder.dart';
+import '../../universe/use.dart';
+import '../../world.dart';
+import '../abstract_value_domain.dart';
+
+class PowersetValue implements AbstractValue {
+ final AbstractValue _abstractValue;
+ final int _powersetBits;
+ const PowersetValue(this._abstractValue, this._powersetBits);
+
+ @override
+ bool operator ==(var other) {
+ if (identical(this, other)) return true;
+ if (other is! PowersetValue) return false;
+ PowersetValue otherPowerset = other;
+ return other is PowersetValue &&
+ _abstractValue == otherPowerset._abstractValue &&
+ _powersetBits == otherPowerset._powersetBits;
+ }
+
+ @override
+ int get hashCode {
+ return _abstractValue.hashCode * _powersetBits.hashCode;
+ }
+
+ @override
+ String toString() =>
+ '[Powerset of ${_abstractValue.toString()} with bits ${_powersetBits}]';
+}
+
+AbstractValue unwrapOrNull(PowersetValue powerset) {
+ return powerset == null ? null : powerset._abstractValue;
+}
+
+PowersetValue wrapOrNull(AbstractValue abstractValue, int powersetBits) {
+ return abstractValue == null
+ ? null
+ : PowersetValue(abstractValue, powersetBits);
+}
+
+class PowersetDomain implements AbstractValueDomain {
+ final AbstractValueDomain _abstractValueDomain;
+ const PowersetDomain(this._abstractValueDomain);
+
+ @override
+ AbstractValue get dynamicType {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.dynamicType;
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ void writeAbstractValueToDataSink(
+ DataSink sink, covariant PowersetValue value) {
+ _abstractValueDomain.writeAbstractValueToDataSink(
+ sink, value._abstractValue);
+ }
+
+ @override
+ AbstractValue readAbstractValueFromDataSource(DataSource source) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.readAbstractValueFromDataSource(source);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ String getCompactText(covariant PowersetValue value) =>
+ _abstractValueDomain.getCompactText(value._abstractValue);
+
+ @override
+ AbstractBool isFixedLengthJsIndexable(covariant PowersetValue value) =>
+ _abstractValueDomain.isFixedLengthJsIndexable(value._abstractValue);
+
+ @override
+ AbstractBool isJsIndexableAndIterable(covariant PowersetValue value) =>
+ _abstractValueDomain.isJsIndexableAndIterable(unwrapOrNull(value));
+
+ @override
+ AbstractBool isJsIndexable(covariant PowersetValue value) =>
+ _abstractValueDomain.isJsIndexable(value._abstractValue);
+
+ @override
+ MemberEntity locateSingleMember(
+ covariant PowersetValue receiver, Selector selector) =>
+ _abstractValueDomain.locateSingleMember(
+ receiver._abstractValue, selector);
+
+ @override
+ AbstractBool isIn(
+ covariant PowersetValue subset, covariant PowersetValue superset) =>
+ _abstractValueDomain.isIn(subset._abstractValue, superset._abstractValue);
+
+ @override
+ AbstractBool needsNoSuchMethodHandling(
+ covariant PowersetValue receiver, Selector selector) =>
+ _abstractValueDomain.needsNoSuchMethodHandling(
+ receiver._abstractValue, selector);
+
+ @override
+ AbstractBool isTargetingMember(
+ covariant PowersetValue receiver, MemberEntity member, Name name) =>
+ _abstractValueDomain.isTargetingMember(
+ receiver._abstractValue, member, name);
+
+ @override
+ AbstractValue computeReceiver(Iterable<MemberEntity> members) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.computeReceiver(members);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ PrimitiveConstantValue getPrimitiveValue(covariant PowersetValue value) =>
+ _abstractValueDomain.getPrimitiveValue(value._abstractValue);
+
+ @override
+ AbstractValue createPrimitiveValue(
+ covariant PowersetValue originalValue, PrimitiveConstantValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createPrimitiveValue(
+ originalValue._abstractValue, value);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isPrimitiveValue(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveValue(value._abstractValue);
+
+ @override
+ MemberEntity getAllocationElement(covariant PowersetValue value) =>
+ _abstractValueDomain.getAllocationElement(value._abstractValue);
+
+ @override
+ Object getAllocationNode(covariant PowersetValue value) =>
+ _abstractValueDomain.getAllocationNode(value._abstractValue);
+
+ @override
+ AbstractValue getGeneralization(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getGeneralization(unwrapOrNull(value));
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isSpecializationOf(covariant PowersetValue specialization,
+ covariant PowersetValue generalization) =>
+ _abstractValueDomain.isSpecializationOf(
+ specialization._abstractValue, generalization._abstractValue);
+
+ @override
+ AbstractValue getDictionaryValueForKey(
+ covariant PowersetValue value, String key) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.getDictionaryValueForKey(
+ value._abstractValue, key);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool containsDictionaryKey(covariant PowersetValue value, String key) =>
+ _abstractValueDomain.containsDictionaryKey(value._abstractValue, key);
+
+ @override
+ AbstractValue createDictionaryValue(
+ covariant PowersetValue originalValue,
+ Object allocationNode,
+ MemberEntity allocationElement,
+ covariant PowersetValue key,
+ covariant PowersetValue value,
+ covariant Map<String, AbstractValue> mappings) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createDictionaryValue(
+ originalValue._abstractValue,
+ allocationNode,
+ allocationElement,
+ key._abstractValue,
+ value._abstractValue, {
+ for (var entry in mappings.entries)
+ entry.key: (entry.value as PowersetValue)._abstractValue
+ });
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isDictionary(covariant PowersetValue value) =>
+ _abstractValueDomain.isDictionary(value._abstractValue);
+
+ @override
+ AbstractValue getMapValueType(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getMapValueType(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue getMapKeyType(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getMapKeyType(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createMapValue(
+ covariant PowersetValue originalValue,
+ Object allocationNode,
+ MemberEntity allocationElement,
+ covariant PowersetValue key,
+ covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createMapValue(
+ originalValue._abstractValue,
+ allocationNode,
+ allocationElement,
+ key._abstractValue,
+ value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isMap(covariant PowersetValue value) =>
+ _abstractValueDomain.isMap(value._abstractValue);
+
+ @override
+ AbstractValue getSetElementType(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getSetElementType(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createSetValue(
+ covariant PowersetValue originalValue,
+ Object allocationNode,
+ MemberEntity allocationElement,
+ covariant PowersetValue elementType) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createSetValue(
+ originalValue._abstractValue,
+ allocationNode,
+ allocationElement,
+ elementType._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isSet(covariant PowersetValue value) =>
+ _abstractValueDomain.isSet(value._abstractValue);
+
+ @override
+ int getContainerLength(covariant PowersetValue value) =>
+ _abstractValueDomain.getContainerLength(value._abstractValue);
+
+ @override
+ AbstractValue getContainerElementType(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getContainerElementType(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createContainerValue(
+ covariant PowersetValue originalValue,
+ Object allocationNode,
+ MemberEntity allocationElement,
+ covariant PowersetValue elementType,
+ int length) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createContainerValue(
+ originalValue._abstractValue,
+ allocationNode,
+ allocationElement,
+ elementType._abstractValue,
+ length);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ bool isContainer(covariant PowersetValue value) =>
+ _abstractValueDomain.isContainer(value._abstractValue);
+
+ @override
+ AbstractValue computeAbstractValueForConstant(covariant ConstantValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.computeAbstractValueForConstant(value);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue getAbstractValueForNativeMethodParameterType(DartType type) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.getAbstractValueForNativeMethodParameterType(type);
+ return wrapOrNull(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractBool containsAll(covariant PowersetValue a) =>
+ _abstractValueDomain.containsAll(a._abstractValue);
+
+ @override
+ AbstractBool areDisjoint(
+ covariant PowersetValue a, covariant PowersetValue b) =>
+ _abstractValueDomain.areDisjoint(a._abstractValue, b._abstractValue);
+
+ @override
+ AbstractValue intersection(
+ covariant PowersetValue a, covariant PowersetValue b) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.intersection(a._abstractValue, b._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue unionOfMany(covariant Iterable<AbstractValue> values) {
+ List<AbstractValue> unwrapped_Values = values
+ .map((element) => (element as PowersetValue)._abstractValue)
+ .toList();
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.unionOfMany(unwrapped_Values);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue union(covariant PowersetValue a, covariant PowersetValue b) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.union(a._abstractValue, b._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractBool isPrimitiveOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isStringOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isStringOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isString(covariant PowersetValue value) =>
+ _abstractValueDomain.isString(value._abstractValue);
+
+ @override
+ AbstractBool isBooleanOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isBooleanOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isBoolean(covariant PowersetValue value) =>
+ _abstractValueDomain.isBoolean(value._abstractValue);
+
+ @override
+ AbstractBool isDoubleOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isDoubleOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isDouble(covariant PowersetValue value) =>
+ _abstractValueDomain.isDouble(value._abstractValue);
+
+ @override
+ AbstractBool isNumberOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isNumberOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isNumber(covariant PowersetValue value) =>
+ _abstractValueDomain.isNumber(value._abstractValue);
+
+ @override
+ AbstractBool isIntegerOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isIntegerOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isPositiveIntegerOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isPositiveIntegerOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isPositiveInteger(covariant PowersetValue value) =>
+ _abstractValueDomain.isPositiveInteger(value._abstractValue);
+
+ @override
+ AbstractBool isUInt31(covariant PowersetValue value) =>
+ _abstractValueDomain.isUInt31(value._abstractValue);
+
+ @override
+ AbstractBool isUInt32(covariant PowersetValue value) =>
+ _abstractValueDomain.isUInt32(value._abstractValue);
+
+ @override
+ AbstractBool isInteger(covariant PowersetValue value) =>
+ _abstractValueDomain.isInteger(value._abstractValue);
+
+ @override
+ AbstractBool isInterceptor(covariant PowersetValue value) =>
+ _abstractValueDomain.isInterceptor(value._abstractValue);
+
+ @override
+ AbstractBool isPrimitiveString(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveString(value._abstractValue);
+
+ @override
+ AbstractBool isArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isArray(value._abstractValue);
+
+ @override
+ AbstractBool isMutableIndexable(covariant PowersetValue value) =>
+ _abstractValueDomain.isMutableIndexable(value._abstractValue);
+
+ @override
+ AbstractBool isMutableArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isMutableArray(value._abstractValue);
+
+ @override
+ AbstractBool isExtendableArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isExtendableArray(value._abstractValue);
+
+ @override
+ AbstractBool isFixedArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isFixedArray(value._abstractValue);
+
+ @override
+ AbstractBool isIndexablePrimitive(covariant PowersetValue value) =>
+ _abstractValueDomain.isIndexablePrimitive(value._abstractValue);
+
+ @override
+ AbstractBool isPrimitiveArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveArray(value._abstractValue);
+
+ @override
+ AbstractBool isPrimitiveBoolean(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveBoolean(value._abstractValue);
+
+ @override
+ AbstractBool isPrimitiveNumber(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitiveNumber(value._abstractValue);
+
+ @override
+ AbstractBool isPrimitive(covariant PowersetValue value) =>
+ _abstractValueDomain.isPrimitive(value._abstractValue);
+
+ @override
+ AbstractBool isNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isNull(value._abstractValue);
+
+ @override
+ ClassEntity getExactClass(covariant PowersetValue value) =>
+ _abstractValueDomain.getExactClass(value._abstractValue);
+
+ @override
+ AbstractBool isExactOrNull(covariant PowersetValue value) =>
+ _abstractValueDomain.isExactOrNull(value._abstractValue);
+
+ @override
+ AbstractBool isExact(covariant PowersetValue value) =>
+ _abstractValueDomain.isExact(value._abstractValue);
+
+ @override
+ AbstractBool isEmpty(covariant PowersetValue value) =>
+ _abstractValueDomain.isEmpty(value._abstractValue);
+
+ @override
+ AbstractBool isInstanceOf(covariant PowersetValue value, ClassEntity cls) =>
+ _abstractValueDomain.isInstanceOf(value._abstractValue, cls);
+
+ @override
+ AbstractBool isInstanceOfOrNull(
+ covariant PowersetValue value, ClassEntity cls) =>
+ _abstractValueDomain.isInstanceOfOrNull(value._abstractValue, cls);
+
+ @override
+ AbstractBool containsOnlyType(
+ covariant PowersetValue value, ClassEntity cls) =>
+ _abstractValueDomain.containsOnlyType(value._abstractValue, cls);
+
+ @override
+ AbstractBool containsType(covariant PowersetValue value, ClassEntity cls) =>
+ _abstractValueDomain.containsType(value._abstractValue, cls);
+
+ @override
+ AbstractValue includeNull(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.includeNull(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue excludeNull(covariant PowersetValue value) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.excludeNull(value._abstractValue);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractBool couldBeTypedArray(covariant PowersetValue value) =>
+ _abstractValueDomain.couldBeTypedArray(value._abstractValue);
+
+ @override
+ AbstractBool isTypedArray(covariant PowersetValue value) =>
+ _abstractValueDomain.isTypedArray(value._abstractValue);
+
+ @override
+ AbstractValue createNullableSubtype(ClassEntity cls) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.createNullableSubtype(cls);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createNonNullSubtype(ClassEntity cls) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.createNonNullSubtype(cls);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createNonNullSubclass(ClassEntity cls) {
+ int powersetBits = 0;
+ AbstractValue abstractValue =
+ _abstractValueDomain.createNonNullSubclass(cls);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createNullableExact(ClassEntity cls) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createNullableExact(cls);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValue createNonNullExact(ClassEntity cls) {
+ int powersetBits = 0;
+ AbstractValue abstractValue = _abstractValueDomain.createNonNullExact(cls);
+ return PowersetValue(abstractValue, powersetBits);
+ }
+
+ @override
+ AbstractValueWithPrecision createFromStaticType(DartType type,
+ {ClassRelation classRelation = ClassRelation.subtype, bool nullable}) {
+ int powersetBits = 0;
+ var unwrapped = _abstractValueDomain.createFromStaticType(type,
+ classRelation: classRelation, nullable: nullable);
+ return AbstractValueWithPrecision(
+ PowersetValue(unwrapped.abstractValue, powersetBits),
+ unwrapped.isPrecise);
+ }
+
+ @override
+ AbstractValue get asyncStarStreamType =>
+ PowersetValue(_abstractValueDomain.asyncStarStreamType, 0);
+
+ @override
+ AbstractValue get asyncFutureType =>
+ PowersetValue(_abstractValueDomain.asyncFutureType, 0);
+
+ @override
+ AbstractValue get syncStarIterableType =>
+ PowersetValue(_abstractValueDomain.syncStarIterableType, 0);
+
+ @override
+ AbstractValue get emptyType =>
+ PowersetValue(_abstractValueDomain.emptyType, 0);
+
+ @override
+ AbstractValue get constMapType =>
+ PowersetValue(_abstractValueDomain.constMapType, 0);
+
+ @override
+ AbstractValue get constSetType =>
+ PowersetValue(_abstractValueDomain.constSetType, 0);
+
+ @override
+ AbstractValue get constListType =>
+ PowersetValue(_abstractValueDomain.constListType, 0);
+
+ @override
+ AbstractValue get positiveIntType =>
+ PowersetValue(_abstractValueDomain.positiveIntType, 0);
+
+ @override
+ AbstractValue get uint32Type =>
+ PowersetValue(_abstractValueDomain.uint32Type, 0);
+
+ @override
+ AbstractValue get uint31Type =>
+ PowersetValue(_abstractValueDomain.uint31Type, 0);
+
+ @override
+ AbstractValue get fixedListType =>
+ PowersetValue(_abstractValueDomain.fixedListType, 0);
+
+ @override
+ AbstractValue get growableListType =>
+ PowersetValue(_abstractValueDomain.growableListType, 0);
+
+ @override
+ AbstractValue get nullType => PowersetValue(_abstractValueDomain.nullType, 0);
+
+ @override
+ AbstractValue get nonNullType =>
+ PowersetValue(_abstractValueDomain.nonNullType, 0);
+
+ @override
+ AbstractValue get mapType => PowersetValue(_abstractValueDomain.mapType, 0);
+
+ @override
+ AbstractValue get setType => PowersetValue(_abstractValueDomain.setType, 0);
+
+ @override
+ AbstractValue get listType => PowersetValue(_abstractValueDomain.listType, 0);
+
+ @override
+ AbstractValue get stringType =>
+ PowersetValue(_abstractValueDomain.stringType, 0);
+
+ @override
+ AbstractValue get numType => PowersetValue(_abstractValueDomain.numType, 0);
+
+ @override
+ AbstractValue get doubleType =>
+ PowersetValue(_abstractValueDomain.doubleType, 0);
+
+ @override
+ AbstractValue get intType => PowersetValue(_abstractValueDomain.intType, 0);
+
+ @override
+ AbstractValue get boolType => PowersetValue(_abstractValueDomain.boolType, 0);
+
+ @override
+ AbstractValue get functionType =>
+ PowersetValue(_abstractValueDomain.functionType, 0);
+
+ @override
+ AbstractValue get typeType => PowersetValue(_abstractValueDomain.typeType, 0);
+}
+
+class PowersetStrategy implements AbstractValueStrategy {
+ final AbstractValueStrategy _abstractValueStrategy;
+ const PowersetStrategy(this._abstractValueStrategy);
+
+ @override
+ AbstractValueDomain createDomain(JClosedWorld closedWorld) {
+ return PowersetDomain(_abstractValueStrategy.createDomain(closedWorld));
+ }
+
+ @override
+ SelectorConstraintsStrategy createSelectorStrategy() {
+ return PowersetsSelectorStrategy(
+ _abstractValueStrategy.createSelectorStrategy());
+ }
+}
+
+class PowersetsSelectorStrategy implements SelectorConstraintsStrategy {
+ final SelectorConstraintsStrategy _selectorConstraintsStrategy;
+ const PowersetsSelectorStrategy(this._selectorConstraintsStrategy);
+
+ @override
+ UniverseSelectorConstraints createSelectorConstraints(
+ Selector selector, Object initialConstraint) {
+ return PowersetsUniverseSelectorConstraints(
+ _selectorConstraintsStrategy.createSelectorConstraints(
+ selector,
+ initialConstraint == null
+ ? null
+ : (initialConstraint as PowersetValue)._abstractValue));
+ }
+
+ @override
+ bool appliedUnnamed(DynamicUse dynamicUse, MemberEntity member,
+ covariant JClosedWorld world) {
+ return _selectorConstraintsStrategy.appliedUnnamed(
+ dynamicUse.withReceiverConstraint(
+ unwrapOrNull(dynamicUse.receiverConstraint)),
+ member,
+ world);
+ }
+}
+
+class PowersetsUniverseSelectorConstraints
+ implements UniverseSelectorConstraints {
+ final UniverseSelectorConstraints _universeSelectorConstraints;
+ const PowersetsUniverseSelectorConstraints(this._universeSelectorConstraints);
+
+ @override
+ bool addReceiverConstraint(Object constraint) =>
+ _universeSelectorConstraints.addReceiverConstraint(constraint == null
+ ? null
+ : (constraint as PowersetValue)._abstractValue);
+
+ @override
+ bool needsNoSuchMethodHandling(Selector selector, World world) =>
+ _universeSelectorConstraints.needsNoSuchMethodHandling(selector, world);
+
+ @override
+ bool canHit(MemberEntity element, Name name, World world) =>
+ _universeSelectorConstraints.canHit(element, name, world);
+
+ @override
+ String toString() => 'PowersetsUniverseSelectorConstraints:$hashCode';
+}
diff --git a/pkg/compiler/lib/src/js_emitter/model.dart b/pkg/compiler/lib/src/js_emitter/model.dart
index 7abd26f..7479339 100644
--- a/pkg/compiler/lib/src/js_emitter/model.dart
+++ b/pkg/compiler/lib/src/js_emitter/model.dart
@@ -198,12 +198,13 @@
final String uri;
final List<StaticMethod> statics;
final List<Class> classes;
+ final List<ClassTypeData> classTypeData;
@override
final List<Field> staticFieldsForReflection;
Library(this.element, this.uri, this.statics, this.classes,
- this.staticFieldsForReflection);
+ this.classTypeData, this.staticFieldsForReflection);
@override
String toString() {
@@ -239,12 +240,28 @@
}
}
-// TODO(fishythefish, sra): Split type information into separate model object.
+class ClassTypeData {
+ /// The element should only be used during the transition to the new model.
+ /// Uses indicate missing information in the model.
+ final ClassEntity element;
+
+ final ClassChecks classChecks;
+ final Set<TypeVariableType> namedTypeVariables = {};
+
+ ClassTypeData(this.element, this.classChecks);
+
+ bool isTriviallyChecked(CommonElements commonElements) =>
+ classChecks.checks.every((TypeCheck check) =>
+ check.cls == commonElements.objectClass || check.cls == element);
+}
+
class Class implements FieldContainer {
/// The element should only be used during the transition to the new model.
/// Uses indicate missing information in the model.
final ClassEntity element;
+ final ClassTypeData typeData;
+
final js.Name name;
final Holder holder;
Class _superclass;
@@ -252,8 +269,6 @@
final List<Method> methods;
final List<Field> fields;
final List<StubMethod> isChecks;
- final ClassChecks classChecksNewRti;
- final Set<TypeVariableType> namedTypeVariablesNewRti = {};
final List<StubMethod> checkedSetters;
/// Stub methods for this class that are call stubs for getters.
@@ -295,6 +310,7 @@
Class(
this.element,
+ this.typeData,
this.name,
this.holder,
this.methods,
@@ -304,7 +320,6 @@
this.noSuchMethodStubs,
this.checkedSetters,
this.isChecks,
- this.classChecksNewRti,
this.functionTypeIndex,
{this.hasRtiField,
this.onlyForRti,
@@ -323,10 +338,6 @@
bool get isSimpleMixinApplication => false;
- bool isTriviallyChecked(CommonElements commonElements) =>
- classChecksNewRti.checks.every((TypeCheck check) =>
- check.cls == commonElements.objectClass || check.cls == element);
-
Class get superclass => _superclass;
void setSuperclass(Class superclass) {
@@ -351,6 +362,7 @@
class MixinApplication extends Class {
MixinApplication(
ClassEntity element,
+ ClassTypeData typeData,
js.Name name,
Holder holder,
List<Field> instanceFields,
@@ -358,7 +370,6 @@
List<StubMethod> callStubs,
List<StubMethod> checkedSetters,
List<StubMethod> isChecks,
- ClassChecks classChecksNewRti,
js.Expression functionTypeIndex,
{bool hasRtiField,
bool onlyForRti,
@@ -366,6 +377,7 @@
bool isDirectlyInstantiated})
: super(
element,
+ typeData,
name,
holder,
const <Method>[],
@@ -375,7 +387,6 @@
const <StubMethod>[],
checkedSetters,
isChecks,
- classChecksNewRti,
functionTypeIndex,
hasRtiField: hasRtiField,
onlyForRti: onlyForRti,
diff --git a/pkg/compiler/lib/src/js_emitter/native_emitter.dart b/pkg/compiler/lib/src/js_emitter/native_emitter.dart
index 84ff8fe..9223c96 100644
--- a/pkg/compiler/lib/src/js_emitter/native_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/native_emitter.dart
@@ -37,9 +37,10 @@
// Caches the methods that have a native body.
Set<FunctionEntity> nativeMethods = new Set<FunctionEntity>();
- // Type metadata redirections, where the key is the class being redirected to
- // and the value is the list of classes being redirected.
- final Map<Class, List<Class>> typeRedirections = {};
+ // Type metadata redirections, where the key is the class type data being
+ // redirected to and the value is the list of class type data being
+ // redirected.
+ final Map<ClassTypeData, List<ClassTypeData>> typeRedirections = {};
NativeEmitter(
this._emitterTask, this._closedWorld, this._nativeCodegenEnqueuer);
@@ -157,19 +158,20 @@
neededClasses.add(cls);
neededClasses.add(cls.superclass);
nonLeafClasses.add(cls.superclass);
- } else if (!cls.isTriviallyChecked(_commonElements) ||
- cls.namedTypeVariablesNewRti.isNotEmpty) {
+ } else if (!cls.typeData.isTriviallyChecked(_commonElements) ||
+ cls.typeData.namedTypeVariables.isNotEmpty) {
// The class is not marked 'needed', but we still need it in the type
// metadata.
- // Redirect this class (and all classes which would have redirected to
- // this class) to its superclass. Because we have a post-order visit,
- // this eventually causes all such native classes to redirect to their
- // leaf interceptors.
- List<Class> redirectedClasses = typeRedirections[cls] ?? [];
- redirectedClasses.add(cls);
- typeRedirections[cls.superclass] = redirectedClasses;
- typeRedirections.remove(cls);
+ // Redirect this class type data (and all class type data which would
+ // have redirected to this class type data) to its superclass. Because
+ // we have a post-order visit, this eventually causes all such native
+ // classes to redirect to their leaf interceptors.
+ List<ClassTypeData> redirectedClasses =
+ typeRedirections[cls.typeData] ?? [];
+ redirectedClasses.add(cls.typeData);
+ typeRedirections[cls.superclass.typeData] = redirectedClasses;
+ typeRedirections.remove(cls.typeData);
}
}
diff --git a/pkg/compiler/lib/src/js_emitter/program_builder/collector.dart b/pkg/compiler/lib/src/js_emitter/program_builder/collector.dart
index 49a1d63..b1aaa3b 100644
--- a/pkg/compiler/lib/src/js_emitter/program_builder/collector.dart
+++ b/pkg/compiler/lib/src/js_emitter/program_builder/collector.dart
@@ -9,6 +9,7 @@
///
/// The code for the containing (used) methods must exist in the `universe`.
class Collector {
+ final CompilerOptions _options;
final JCommonElements _commonElements;
final JElementEnvironment _elementEnvironment;
final OutputUnitData _outputUnitData;
@@ -27,6 +28,7 @@
// This field is set in [computeNeededDeclarations].
Set<ClassEntity> classesOnlyNeededForConstructor;
final Map<OutputUnit, List<ClassEntity>> outputClassLists = {};
+ final Map<OutputUnit, List<ClassEntity>> outputClassTypeLists = {};
final Map<OutputUnit, List<ConstantValue>> outputConstantLists = {};
final Map<OutputUnit, List<MemberEntity>> outputStaticLists = {};
final Map<OutputUnit, List<FieldEntity>> outputStaticNonFinalFieldLists = {};
@@ -41,6 +43,7 @@
final List<ClassEntity> nativeClassesAndSubclasses = [];
Collector(
+ this._options,
this._commonElements,
this._elementEnvironment,
this._outputUnitData,
@@ -134,6 +137,14 @@
}
}
+ Map<OutputUnit, List<ClassEntity>> get _outputListsForClassType {
+ if (_options.deferClassTypes) {
+ return outputClassTypeLists;
+ } else {
+ return outputClassLists;
+ }
+ }
+
/// Compute all the classes and typedefs that must be emitted.
void computeNeededDeclarations() {
Set<ClassEntity> backendTypeHelpers =
@@ -147,18 +158,11 @@
.where(computeClassFilter(backendTypeHelpers))
.toSet();
- void addClassWithSuperclasses(ClassEntity cls) {
- neededClasses.add(cls);
- for (ClassEntity superclass = _elementEnvironment.getSuperClass(cls);
- superclass != null;
- superclass = _elementEnvironment.getSuperClass(superclass)) {
- neededClasses.add(superclass);
- }
- }
-
void addClassesWithSuperclasses(Iterable<ClassEntity> classes) {
for (ClassEntity cls in classes) {
- addClassWithSuperclasses(cls);
+ neededClasses.add(cls);
+ _elementEnvironment.forEachSuperClass(
+ cls, (superClass) => neededClasses.add(superClass));
}
}
@@ -199,8 +203,11 @@
List<ClassEntity> sortedClasses = _sorter.sortClasses(neededClasses);
for (ClassEntity cls in sortedClasses) {
- if (_nativeData.isNativeOrExtendsNative(cls) &&
- !classesOnlyNeededForRti.contains(cls) &&
+ if (classesOnlyNeededForRti.contains(cls)) {
+ _outputListsForClassType
+ .putIfAbsent(_outputUnitData.outputUnitForClassType(cls), () => [])
+ .add(cls);
+ } else if (_nativeData.isNativeOrExtendsNative(cls) &&
!classesOnlyNeededForConstructor.contains(cls)) {
// For now, native classes and related classes cannot be deferred.
nativeClassesAndSubclasses.add(cls);
@@ -285,7 +292,9 @@
outputLibraryLists.putIfAbsent(unit, () => {}).add(library);
});
neededClasses.forEach((ClassEntity element) {
- OutputUnit unit = _outputUnitData.outputUnitForClass(element);
+ OutputUnit unit = classesOnlyNeededForRti.contains(element)
+ ? _outputUnitData.outputUnitForClassType(element)
+ : _outputUnitData.outputUnitForClass(element);
LibraryEntity library = element.library;
outputLibraryLists.putIfAbsent(unit, () => {}).add(library);
});
diff --git a/pkg/compiler/lib/src/js_emitter/program_builder/program_builder.dart b/pkg/compiler/lib/src/js_emitter/program_builder/program_builder.dart
index e2ad389..5351885 100644
--- a/pkg/compiler/lib/src/js_emitter/program_builder/program_builder.dart
+++ b/pkg/compiler/lib/src/js_emitter/program_builder/program_builder.dart
@@ -135,6 +135,7 @@
this._rtiNeededClasses,
this._mainFunction)
: this.collector = new Collector(
+ _options,
_commonElements,
_elementEnvironment,
_outputUnitData,
@@ -153,6 +154,10 @@
/// update the superclass in the [Class].
final Map<ClassEntity, Class> _classes = <ClassEntity, Class>{};
+ /// Mapping from [ClassEntity] to constructed [ClassTypeData] object. Used to build
+ /// libraries.
+ final Map<ClassEntity, ClassTypeData> _classTypeData = {};
+
/// Mapping from [OutputUnit] to constructed [Fragment]. We need this to
/// generate the deferredLoadingMap (to know which hunks to load).
final Map<OutputUnit, Fragment> _outputs = <OutputUnit, Fragment>{};
@@ -184,6 +189,7 @@
_closedWorld.outputUnitData.outputUnits
.forEach(_registry.registerOutputUnit);
collector.outputClassLists.forEach(_registry.registerClasses);
+ collector.outputClassTypeLists.forEach(_registry.registerClassTypes);
collector.outputStaticLists.forEach(_registry.registerMembers);
collector.outputConstantLists.forEach(_registerConstants);
collector.outputStaticNonFinalFieldLists.forEach(_registry.registerMembers);
@@ -199,6 +205,11 @@
classes.forEach(_buildClass);
});
+ collector.outputClassTypeLists
+ .forEach((OutputUnit _, List<ClassEntity> types) {
+ types.forEach(_buildClassTypeData);
+ });
+
// Resolve the superclass references after we've processed all the classes.
_classes.forEach((ClassEntity cls, Class c) {
ClassEntity superclass = _elementEnvironment.getSuperClass(cls);
@@ -473,8 +484,9 @@
List<Library> libraries = new List<Library>(librariesMap.length);
int count = 0;
librariesMap.forEach((LibraryEntity library, List<ClassEntity> classes,
- List<MemberEntity> members) {
- libraries[count++] = _buildLibrary(library, classes, members);
+ List<MemberEntity> members, List<ClassEntity> classTypeElements) {
+ libraries[count++] =
+ _buildLibrary(library, classes, members, classTypeElements);
});
return libraries;
}
@@ -500,8 +512,8 @@
interceptorClass?.isChecks?.addAll(_jsInteropIsChecks);
Set<String> stubNames = {};
- librariesMap
- .forEach((LibraryEntity library, List<ClassEntity> classElements, _) {
+ librariesMap.forEach((LibraryEntity library,
+ List<ClassEntity> classElements, _memberElement, _typeElement) {
for (ClassEntity cls in classElements) {
if (_nativeData.isJsInteropClass(cls)) {
_elementEnvironment.forEachLocalClassMember(cls,
@@ -601,7 +613,7 @@
// Note that a library-element may have multiple [Library]s, if it is split
// into multiple output units.
Library _buildLibrary(LibraryEntity library, List<ClassEntity> classElements,
- List<MemberEntity> memberElements) {
+ List<MemberEntity> memberElements, List<ClassEntity> classTypeElements) {
String uri = library.canonicalUri.toString();
List<StaticMethod> statics = memberElements
@@ -621,12 +633,17 @@
!cls.isNative || !_unneededNativeClasses.contains(cls))
.toList(growable: false);
+ List<ClassTypeData> classTypeData = classTypeElements
+ .map((ClassEntity classTypeElement) => _classTypeData[classTypeElement])
+ .toList();
+ classTypeData.addAll(classes.map((Class cls) => cls.typeData).toList());
+
bool visitStatics = true;
List<Field> staticFieldsForReflection =
_buildFields(library: library, visitStatics: visitStatics);
- return new Library(
- library, uri, statics, classes, staticFieldsForReflection);
+ return new Library(library, uri, statics, classes, classTypeData,
+ staticFieldsForReflection);
}
bool _isSoftDeferred(ClassEntity element) {
@@ -636,9 +653,12 @@
Class _buildClass(ClassEntity cls) {
bool onlyForConstructor =
collector.classesOnlyNeededForConstructor.contains(cls);
- bool onlyForRti = collector.classesOnlyNeededForRti.contains(cls);
+ bool onlyForRti = _options.deferClassTypes
+ ? false
+ : collector.classesOnlyNeededForRti.contains(cls);
bool hasRtiField = _rtiNeed.classNeedsTypeArguments(cls);
if (_nativeData.isJsInteropClass(cls)) {
+ // TODO(joshualitt): Can we just emit JSInteropClasses as types?
// TODO(jacobr): check whether the class has any active static fields
// if it does not we can suppress it completely.
onlyForRti = true;
@@ -793,6 +813,7 @@
bool isInstantiated = !_nativeData.isJsInteropClass(cls) &&
_codegenWorld.directlyInstantiatedClasses.contains(cls);
+ ClassTypeData typeData = ClassTypeData(cls, _rtiChecks.requiredChecks[cls]);
Class result;
if (_elementEnvironment.isMixinApplication(cls) &&
!onlyForConstructorOrRti &&
@@ -803,6 +824,7 @@
result = new MixinApplication(
cls,
+ typeData,
name,
holder,
instanceFields,
@@ -810,7 +832,6 @@
callStubs,
checkedSetters,
isChecks,
- _rtiChecks.requiredChecks[cls],
typeTests.functionTypeIndex,
isDirectlyInstantiated: isInstantiated,
hasRtiField: hasRtiField,
@@ -819,6 +840,7 @@
} else {
result = new Class(
cls,
+ typeData,
name,
holder,
methods,
@@ -828,7 +850,6 @@
noSuchMethodStubs,
checkedSetters,
isChecks,
- _rtiChecks.requiredChecks[cls],
typeTests.functionTypeIndex,
isDirectlyInstantiated: isInstantiated,
hasRtiField: hasRtiField,
@@ -843,6 +864,10 @@
return result;
}
+ void _buildClassTypeData(ClassEntity cls) {
+ _classTypeData[cls] = ClassTypeData(cls, _rtiChecks.requiredChecks[cls]);
+ }
+
void associateNamedTypeVariablesNewRti() {
for (TypeVariableType typeVariable in _codegenWorld.namedTypeVariablesNewRti
.union(_lateNamedTypeVariablesNewRti)) {
@@ -853,8 +878,13 @@
: _classHierarchy.subclassesOf(declaration);
for (ClassEntity entity in subtypes) {
Class cls = _classes[entity];
- if (cls == null) continue;
- cls.namedTypeVariablesNewRti.add(typeVariable);
+ if (cls != null) {
+ cls.typeData.namedTypeVariables.add(typeVariable);
+ }
+ ClassTypeData classTypeData = _classTypeData[entity];
+ if (classTypeData != null) {
+ classTypeData.namedTypeVariables.add(typeVariable);
+ }
}
}
}
diff --git a/pkg/compiler/lib/src/js_emitter/program_builder/registry.dart b/pkg/compiler/lib/src/js_emitter/program_builder/registry.dart
index 13bc633..c738517 100644
--- a/pkg/compiler/lib/src/js_emitter/program_builder/registry.dart
+++ b/pkg/compiler/lib/src/js_emitter/program_builder/registry.dart
@@ -5,14 +5,18 @@
part of dart2js.js_emitter.program_builder;
class LibraryContents {
- final List<ClassEntity> classes = <ClassEntity>[];
- final List<MemberEntity> members = <MemberEntity>[];
+ final List<ClassEntity> classes = [];
+ final List<MemberEntity> members = [];
+ final List<ClassEntity> classTypes = [];
}
-/// Maps [LibraryEntity]s to their [ClassEntity]s and [MemberEntity]s.
+/// Maps [LibraryEntity]s to their classes, members, and class types.
///
/// Fundamentally, this class nicely encapsulates a
-/// `Map<LibraryEntity, Pair<List<ClassEntity>, List<MemberEntity>>>`.
+/// `Map<LibraryEntity, Tuple<classes, members, class types>>`.
+///
+/// where both classes and class types are lists of [ClassEntity] and
+/// members is a list of [MemberEntity].
///
/// There exists exactly one instance per [OutputUnit].
class LibrariesMap {
@@ -46,6 +50,10 @@
_getMapping(library).classes.add(element);
}
+ void addClassType(LibraryEntity library, ClassEntity element) {
+ _getMapping(library).classTypes.add(element);
+ }
+
void addMember(LibraryEntity library, MemberEntity element) {
_getMapping(library).members.add(element);
}
@@ -54,9 +62,9 @@
void forEach(
void f(LibraryEntity library, List<ClassEntity> classes,
- List<MemberEntity> members)) {
+ List<MemberEntity> members, List<ClassEntity> classTypeData)) {
_mapping.forEach((LibraryEntity library, LibraryContents mapping) {
- f(library, mapping.classes, mapping.members);
+ f(library, mapping.classes, mapping.members, mapping.classTypes);
});
}
}
@@ -125,6 +133,16 @@
/// Adds all elements to their respective libraries in the correct
/// libraries map.
+ void registerClassTypes(
+ OutputUnit outputUnit, Iterable<ClassEntity> elements) {
+ LibrariesMap targetLibrariesMap = _mapUnitToLibrariesMap(outputUnit);
+ for (ClassEntity element in _sorter.sortClasses(elements)) {
+ targetLibrariesMap.addClassType(element.library, element);
+ }
+ }
+
+ /// Adds all elements to their respective libraries in the correct
+ /// libraries map.
void registerMembers(OutputUnit outputUnit, Iterable<MemberEntity> elements) {
LibrariesMap targetLibrariesMap = _mapUnitToLibrariesMap(outputUnit);
for (MemberEntity element in _sorter.sortMembers(elements)) {
diff --git a/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart b/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart
index 1da9bec..d9bfaab 100644
--- a/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart
+++ b/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart
@@ -263,7 +263,7 @@
@override
bool visitInterfaceType(InterfaceType type, OutputUnit argument) {
- if (_outputUnitData.outputUnitForClass(type.element) != argument) {
+ if (_outputUnitData.outputUnitForClassType(type.element) != argument) {
return false;
}
return visitList(type.typeArguments, argument);
diff --git a/pkg/compiler/lib/src/js_emitter/startup_emitter/fragment_emitter.dart b/pkg/compiler/lib/src/js_emitter/startup_emitter/fragment_emitter.dart
index 0bd06bf..41ddad7 100644
--- a/pkg/compiler/lib/src/js_emitter/startup_emitter/fragment_emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/startup_emitter/fragment_emitter.dart
@@ -1998,15 +1998,15 @@
ClassEntity jsObjectClass = _commonElements.jsJavaScriptObjectClass;
InterfaceType jsObjectType = _elementEnvironment.getThisType(jsObjectClass);
- Map<Class, List<Class>> nativeRedirections =
+ Map<ClassTypeData, List<ClassTypeData>> nativeRedirections =
_nativeEmitter.typeRedirections;
Ruleset ruleset = Ruleset.empty();
Map<ClassEntity, int> erasedTypes = {};
- Iterable<Class> classes =
- fragment.libraries.expand((Library library) => library.classes);
- classes.forEach((Class cls) {
- ClassEntity element = cls.element;
+ Iterable<ClassTypeData> classTypeData =
+ fragment.libraries.expand((Library library) => library.classTypeData);
+ classTypeData.forEach((ClassTypeData typeData) {
+ ClassEntity element = typeData.element;
InterfaceType targetType = _elementEnvironment.getThisType(element);
// TODO(fishythefish): Prune uninstantiated classes.
@@ -2016,7 +2016,7 @@
bool isInterop = _classHierarchy.isSubclassOf(element, jsObjectClass);
- Iterable<TypeCheck> checks = cls.classChecksNewRti?.checks ?? [];
+ Iterable<TypeCheck> checks = typeData.classChecks?.checks ?? [];
Iterable<InterfaceType> supertypes = isInterop
? checks
.map((check) => _elementEnvironment.getJsInteropType(check.cls))
@@ -2024,11 +2024,11 @@
.map((check) => _dartTypes.asInstanceOf(targetType, check.cls));
Map<TypeVariableType, DartType> typeVariables = {};
- Set<TypeVariableType> namedTypeVariables = cls.namedTypeVariablesNewRti;
- nativeRedirections[cls]?.forEach((Class redirectee) {
- namedTypeVariables.addAll(redirectee.namedTypeVariablesNewRti);
+ Set<TypeVariableType> namedTypeVariables = typeData.namedTypeVariables;
+ nativeRedirections[typeData]?.forEach((ClassTypeData redirectee) {
+ namedTypeVariables.addAll(redirectee.namedTypeVariables);
});
- for (TypeVariableType typeVariable in cls.namedTypeVariablesNewRti) {
+ for (TypeVariableType typeVariable in typeData.namedTypeVariables) {
TypeVariableEntity element = typeVariable.element;
InterfaceType supertype = isInterop
? _elementEnvironment.getJsInteropType(element.typeDeclaration)
@@ -2053,8 +2053,9 @@
});
}
- nativeRedirections.forEach((Class target, List<Class> redirectees) {
- for (Class redirectee in redirectees) {
+ nativeRedirections
+ .forEach((ClassTypeData target, List<ClassTypeData> redirectees) {
+ for (ClassTypeData redirectee in redirectees) {
ruleset.addRedirection(redirectee.element, target.element);
}
});
diff --git a/pkg/compiler/lib/src/kernel/element_map_impl.dart b/pkg/compiler/lib/src/kernel/element_map_impl.dart
index 5977113..76e5139 100644
--- a/pkg/compiler/lib/src/kernel/element_map_impl.dart
+++ b/pkg/compiler/lib/src/kernel/element_map_impl.dart
@@ -1913,6 +1913,15 @@
KClassData classData = elementMap.classes.getData(cls);
return classData.isEnumClass;
}
+
+ @override
+ ClassEntity getEffectiveMixinClass(ClassEntity cls) {
+ if (!isMixinApplication(cls)) return null;
+ do {
+ cls = elementMap.getAppliedMixin(cls);
+ } while (isMixinApplication(cls));
+ return cls;
+ }
}
/// [BehaviorBuilder] for kernel based elements.
diff --git a/pkg/compiler/lib/src/kernel/native_basic_data.dart b/pkg/compiler/lib/src/kernel/native_basic_data.dart
index 3d43255..9ebb17d 100644
--- a/pkg/compiler/lib/src/kernel/native_basic_data.dart
+++ b/pkg/compiler/lib/src/kernel/native_basic_data.dart
@@ -156,10 +156,7 @@
elementEnvironment.forEachLocalClassMember(cls, (MemberEntity member) {
String memberName = getJsInteropName(
library, elementEnvironment.getMemberMetadata(member));
- if (memberName != null) {
- reporter.reportErrorMessage(
- member, MessageKind.JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS);
- } else if (member is FunctionEntity) {
+ if (memberName == null && member is FunctionEntity) {
if (member.isExternal &&
!commonElements.isExternalAllowed(member)) {
reporter.reportErrorMessage(
@@ -171,10 +168,7 @@
(ConstructorEntity constructor) {
String memberName = getJsInteropName(
library, elementEnvironment.getMemberMetadata(constructor));
- if (memberName != null) {
- reporter.reportErrorMessage(constructor,
- MessageKind.JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS);
- } else {
+ if (memberName == null) {
if (constructor.isExternal &&
!commonElements.isExternalAllowed(constructor)) {
reporter.reportErrorMessage(
diff --git a/pkg/compiler/lib/src/options.dart b/pkg/compiler/lib/src/options.dart
index a2f9c2c..3e9ab67 100644
--- a/pkg/compiler/lib/src/options.dart
+++ b/pkg/compiler/lib/src/options.dart
@@ -157,6 +157,11 @@
/// This flag is presented to help developers find and fix the affected code.
bool reportInvalidInferredDeferredTypes = false;
+ /// Whether to defer load class types.
+ bool deferClassTypes = false; // default value.
+ bool _deferClassTypes = false;
+ bool _noDeferClassTypes = false;
+
/// Whether to disable inlining during the backend optimizations.
// TODO(sigmund): negate, so all flags are positive
bool disableInlining = false;
@@ -193,7 +198,10 @@
/// Whether to use the trivial abstract value domain.
bool useTrivialAbstractValueDomain = false;
- /// Whether to use the powerset abstract value domain (experimental).
+ /// Whether to use the wrapped abstract value domain (experimental).
+ bool experimentalWrapped = false;
+
+ /// Whether to use the powersets abstract value domain (experimental).
bool experimentalPowersets = false;
/// Whether to disable optimization for need runtime type information.
@@ -426,6 +434,8 @@
..newDeferredSplit = _hasOption(options, Flags.newDeferredSplit)
..reportInvalidInferredDeferredTypes =
_hasOption(options, Flags.reportInvalidInferredDeferredTypes)
+ .._deferClassTypes = _hasOption(options, Flags.deferClassTypes)
+ .._noDeferClassTypes = _hasOption(options, Flags.noDeferClassTypes)
..fatalWarnings = _hasOption(options, Flags.fatalWarnings)
..terseDiagnostics = _hasOption(options, Flags.terse)
..suppressWarnings = _hasOption(options, Flags.suppressWarnings)
@@ -438,6 +448,7 @@
..disableTypeInference = _hasOption(options, Flags.disableTypeInference)
..useTrivialAbstractValueDomain =
_hasOption(options, Flags.useTrivialAbstractValueDomain)
+ ..experimentalWrapped = _hasOption(options, Flags.experimentalWrapped)
..experimentalPowersets = _hasOption(options, Flags.experimentalPowersets)
..disableRtiOptimization =
_hasOption(options, Flags.disableRtiOptimization)
@@ -527,6 +538,10 @@
throw ArgumentError("'${Flags.soundNullSafety}' requires the "
"'non-nullable' experiment to be enabled");
}
+ if (_deferClassTypes && _noDeferClassTypes) {
+ throw ArgumentError("'${Flags.deferClassTypes}' incompatible with "
+ "'${Flags.noDeferClassTypes}'");
+ }
}
void deriveOptions() {
@@ -588,6 +603,9 @@
if (_disableMinification) {
enableMinification = false;
}
+
+ if (_deferClassTypes) deferClassTypes = true;
+ if (_noDeferClassTypes) deferClassTypes = false;
}
/// Returns `true` if warnings and hints are shown for all packages.
diff --git a/pkg/compiler/lib/src/source_file_provider.dart b/pkg/compiler/lib/src/source_file_provider.dart
index 11272be..e227a7d 100644
--- a/pkg/compiler/lib/src/source_file_provider.dart
+++ b/pkg/compiler/lib/src/source_file_provider.dart
@@ -586,3 +586,64 @@
return null;
}
}
+
+/// Adapter to support one or more synthetic uri schemes.
+///
+/// These custom uris map to one or more real directories on the file system,
+/// providing a merged view - or "overlay" file system.
+///
+/// This also allows for hermetic builds which do not encode machine specific
+/// absolute uris by creating a synthetic "root" of the file system.
+///
+/// TODO(sigmund): Remove the [BazelInputProvider] in favor of this.
+/// TODO(sigmund): Remove this and use the common `MultiRootFileSystem`
+/// implementation.
+class MultiRootInputProvider extends SourceFileProvider {
+ final List<Uri> roots;
+ final String markerScheme;
+
+ MultiRootInputProvider(this.markerScheme, List<String> searchPaths)
+ : roots = searchPaths.map(Uri.base.resolve).toList();
+
+ @override
+ Future<api.Input<List<int>>> readFromUri(Uri uri,
+ {InputKind inputKind: InputKind.UTF8}) async {
+ var resolvedUri = uri;
+ if (resolvedUri.scheme == markerScheme) {
+ var path = resolvedUri.path;
+ if (path.startsWith('/')) path = path.substring(1);
+ for (var dir in roots) {
+ var fileUri = dir.resolve(path);
+ if (await new File.fromUri(fileUri).exists()) {
+ resolvedUri = fileUri;
+ break;
+ }
+ }
+ }
+ api.Input<List<int>> result =
+ await readBytesFromUri(resolvedUri, inputKind);
+ switch (inputKind) {
+ case InputKind.UTF8:
+ utf8SourceFiles[uri] = utf8SourceFiles[resolvedUri];
+ break;
+ case InputKind.binary:
+ binarySourceFiles[uri] = binarySourceFiles[resolvedUri];
+ break;
+ }
+ return result;
+ }
+
+ @override
+ api.Input autoReadFromFile(Uri resourceUri) {
+ if (resourceUri.scheme == markerScheme) {
+ var path = resourceUri.path;
+ for (var dir in roots) {
+ var file = dir.resolve(path);
+ if (new File.fromUri(file).existsSync()) {
+ return super.autoReadFromFile(file);
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/lib.dart b/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/lib.dart
new file mode 100644
index 0000000..f920e6b
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/lib.dart
@@ -0,0 +1,96 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+/*member: a:OutputUnit(1, {lib})*/
+a() => print("123");
+
+/*member: b:OutputUnit(1, {lib})*/
+b() => print("123");
+
+/*member: c:OutputUnit(1, {lib})*/
+c() => print("123");
+
+/*member: d:OutputUnit(1, {lib})*/
+d() => print("123");
+
+/*class: B:OutputUnit(1, {lib})*/
+class B {
+ /*member: B.:OutputUnit(1, {lib})*/
+ B() {
+ b();
+ }
+}
+
+/*class: B2:OutputUnit(1, {lib})*/
+/*member: B2.:OutputUnit(1, {lib})*/
+class B2 extends B {
+ // No constructor creates a synthetic constructor that has an implicit
+ // super-call.
+}
+
+/*class: A:OutputUnit(1, {lib})*/
+class A {
+ /*member: A.:OutputUnit(1, {lib})*/
+ A() {
+ a();
+ }
+}
+
+/*class: A2:OutputUnit(1, {lib})*/
+class A2 extends A {
+ // Implicit super call.
+ /*member: A2.:OutputUnit(1, {lib})*/
+ A2();
+}
+
+/*class: C1:OutputUnit(1, {lib})*/
+class C1 {}
+
+/*class: C2:OutputUnit(1, {lib})*/
+class C2 {
+ /*member: C2.:OutputUnit(1, {lib})*/
+ C2() {
+ c();
+ }
+}
+
+/*class: C2p:null*/
+class C2p {
+ C2() {
+ c();
+ }
+}
+
+/*class: C3:OutputUnit(1, {lib})*/
+/*member: C3.:OutputUnit(1, {lib})*/
+class C3 extends C2 with C1 {
+ // Implicit redirecting "super" call via mixin.
+}
+
+/*class: E:OutputUnit(1, {lib})*/
+class E {}
+
+/*class: F:OutputUnit(1, {lib})*/
+class F {}
+
+/*class: G:OutputUnit(1, {lib})*/
+/*member: G.:OutputUnit(1, {lib})*/
+class G extends C3 with C1, E, F {}
+
+/*class: D1:OutputUnit(1, {lib})*/
+class D1 {}
+
+/*class: D2:OutputUnit(1, {lib})*/
+class D2 {
+ /*member: D2.:OutputUnit(1, {lib})*/
+ D2(x) {
+ d();
+ }
+}
+
+// Implicit redirecting "super" call with a parameter via mixin.
+/*class: D3:OutputUnit(1, {lib})*/
+class D3 = D2 with D1;
diff --git a/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/main.dart b/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/main.dart
new file mode 100644
index 0000000..fe41fa5
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/follow_implicit_super_regression_test/main.dart
@@ -0,0 +1,18 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import "lib.dart" deferred as lib;
+
+/*member: main:OutputUnit(main, {})*/
+void main() {
+ lib.loadLibrary().then(/*OutputUnit(main, {})*/ (_) {
+ new lib.A2();
+ new lib.B2();
+ new lib.C3();
+ new lib.D3(10);
+ new lib.G();
+ });
+}
diff --git a/pkg/compiler/test/deferred_loading/data/inteface_type_variable/lib.dart b/pkg/compiler/test/deferred_loading/data/inteface_type_variable/lib.dart
new file mode 100644
index 0000000..97e8353
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/inteface_type_variable/lib.dart
@@ -0,0 +1,41 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+/*class: A:OutputUnit(1, {lib})*/
+/*member: A.:OutputUnit(1, {lib})*/
+class A {}
+
+/*class: I:OutputUnit(1, {lib})*/
+class I<T> {}
+
+/*class: J:OutputUnit(1, {lib})*/
+/*member: J.:OutputUnit(1, {lib})*/
+class J<T> {}
+
+// C needs to include "N", otherwise checking for `is I<A>` will likely cause
+// problems
+/*class: C:OutputUnit(1, {lib})*/
+/*member: C.:OutputUnit(1, {lib})*/
+class C extends A implements I<N> {}
+
+/*class: C1:OutputUnit(1, {lib})*/
+/*member: C1.:OutputUnit(1, {lib})*/
+class C1 extends J<M> implements A {}
+
+/*class: C2:OutputUnit(1, {lib})*/
+/*member: C2.:OutputUnit(1, {lib})*/
+class C2 extends J<M> implements I<N> {}
+
+/*class: N:OutputUnit(1, {lib})*/
+class N extends A {}
+
+/*class: M:OutputUnit(1, {lib})*/
+class M extends A {}
+
+/*member: doCheck1:OutputUnit(1, {lib})*/
+doCheck1(x) => x is I<A>;
+/*member: doCheck2:OutputUnit(1, {lib})*/
+doCheck2(x) => x is J<A>;
diff --git a/pkg/compiler/test/deferred_loading/data/inteface_type_variable/main.dart b/pkg/compiler/test/deferred_loading/data/inteface_type_variable/main.dart
new file mode 100644
index 0000000..d9075e9
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/inteface_type_variable/main.dart
@@ -0,0 +1,28 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'lib.dart' deferred as lib;
+
+/// Regression test: if a type variable is used, but not instantiated, it still
+/// needs to be mapped to the deferred unit where it is used.
+///
+/// If not, we may include it in the main unit and may not see that the base
+/// class is not added to the main unit.
+/*member: main:OutputUnit(main, {})*/
+main() {
+ lib.loadLibrary().then(/*OutputUnit(main, {})*/ (_) {
+ lib.doCheck1(dontInline(new lib.C()));
+ lib.doCheck1(dontInline(new lib.C1()));
+ lib.doCheck1(dontInline(new lib.C2()));
+ lib.doCheck2(dontInline(new lib.C()));
+ lib.doCheck2(dontInline(new lib.C1()));
+ lib.doCheck2(dontInline(new lib.C2()));
+ });
+}
+
+@pragma('dart2js:noInline')
+/*member: dontInline:OutputUnit(main, {})*/
+dontInline(x) => x;
diff --git a/pkg/compiler/test/deferred_loading/data/lazy_types/lib.dart b/pkg/compiler/test/deferred_loading/data/lazy_types/lib.dart
new file mode 100644
index 0000000..f8a57c2
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/lazy_types/lib.dart
@@ -0,0 +1,86 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+/*class: Foo:OutputUnit(1, {libA, libB, libC})*/
+class Foo {
+ /*member: Foo.x:OutputUnit(1, {libA, libB, libC})*/
+ int x;
+ /*member: Foo.:OutputUnit(3, {libB})*/
+ Foo() {
+ x = DateTime.now().millisecond;
+ }
+ /*member: Foo.method:OutputUnit(1, {libA, libB, libC})*/
+ int method() => x;
+}
+
+/*member: isFoo:OutputUnit(1, {libA, libB, libC})*/
+bool isFoo(o) {
+ return o is Foo;
+}
+
+/*member: callFooMethod:OutputUnit(3, {libB})*/
+int callFooMethod() {
+ return Foo().method();
+}
+
+typedef int FunFoo(Foo a);
+typedef int FunFunFoo(FunFoo b, int c);
+
+/*member: isFunFunFoo:OutputUnit(1, {libA, libB, libC})*/
+bool isFunFunFoo(o) {
+ return o is FunFunFoo;
+}
+
+/*class: Aoo:OutputUnit(4, {libB, libC})*/
+class Aoo<T> {}
+
+/*class: Boo:OutputUnit(4, {libB, libC})*/
+class Boo<T> implements Aoo<T> {}
+
+/*class: Coo:OutputUnit(4, {libB, libC})*/
+/*member: Coo.:OutputUnit(6, {libC})*/
+class Coo<T> {}
+
+/*class: Doo:OutputUnit(4, {libB, libC})*/
+/*member: Doo.:OutputUnit(6, {libC})*/
+class Doo<T> extends Coo<T> with Boo<T> {}
+
+/*member: createDooFunFunFoo:OutputUnit(6, {libC})*/
+createDooFunFunFoo() => Doo<FunFunFoo>();
+
+/*class: B:OutputUnit(2, {libA, libC})*/
+/*member: B.:OutputUnit(6, {libC})*/
+class B {}
+
+/*class: B2:OutputUnit(2, {libA, libC})*/
+/*member: B2.:OutputUnit(6, {libC})*/
+class B2 extends B {}
+
+/*class: C1:OutputUnit(2, {libA, libC})*/
+class C1 {}
+
+/*class: C2:OutputUnit(2, {libA, libC})*/
+/*member: C2.:OutputUnit(6, {libC})*/
+class C2 {}
+
+/*class: C3:OutputUnit(2, {libA, libC})*/
+/*member: C3.:OutputUnit(6, {libC})*/
+class C3 extends C2 with C1 {}
+
+/*class: D1:OutputUnit(2, {libA, libC})*/
+class D1 {}
+
+/*class: D2:OutputUnit(2, {libA, libC})*/
+/*member: D2.:OutputUnit(6, {libC})*/
+class D2 {}
+
+/*class: D3:OutputUnit(2, {libA, libC})*/
+class D3 = D2 with D1;
+
+/*member: isMega:OutputUnit(5, {libA})*/
+bool isMega(o) {
+ return o is B2 || o is C3 || o is D3;
+}
diff --git a/pkg/compiler/test/deferred_loading/data/lazy_types/liba.dart b/pkg/compiler/test/deferred_loading/data/lazy_types/liba.dart
new file mode 100644
index 0000000..a712114
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/lazy_types/liba.dart
@@ -0,0 +1,16 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'lib.dart' as lib;
+
+/*member: isFoo:OutputUnit(5, {libA})*/
+bool isFoo(o) => lib.isFoo(o);
+
+/*member: isFunFunFoo:OutputUnit(5, {libA})*/
+bool isFunFunFoo(o) => lib.isFunFunFoo(o);
+
+/*member: isMega:OutputUnit(5, {libA})*/
+bool isMega(o) => lib.isMega(o);
diff --git a/pkg/compiler/test/deferred_loading/data/lazy_types/libb.dart b/pkg/compiler/test/deferred_loading/data/lazy_types/libb.dart
new file mode 100644
index 0000000..591fe47
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/lazy_types/libb.dart
@@ -0,0 +1,19 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'lib.dart' as lib;
+
+/*member: callFooMethod:OutputUnit(3, {libB})*/
+int callFooMethod() => lib.callFooMethod();
+
+/*member: isFoo:OutputUnit(3, {libB})*/
+bool isFoo(o) => lib.isFoo(o);
+
+/*member: isFunFunFoo:OutputUnit(3, {libB})*/
+bool isFunFunFoo(o) => lib.isFunFunFoo(o);
+
+/*member: isDooFunFunFoo:OutputUnit(3, {libB})*/
+bool isDooFunFunFoo(o) => o is lib.Doo<lib.FunFunFoo>;
diff --git a/pkg/compiler/test/deferred_loading/data/lazy_types/libc.dart b/pkg/compiler/test/deferred_loading/data/lazy_types/libc.dart
new file mode 100644
index 0000000..1c04601
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/lazy_types/libc.dart
@@ -0,0 +1,25 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'lib.dart' as lib;
+
+/*member: isFoo:OutputUnit(6, {libC})*/
+bool isFoo(o) => lib.isFoo(o);
+
+/*member: isFunFunFoo:OutputUnit(6, {libC})*/
+bool isFunFunFoo(o) => lib.isFunFunFoo(o);
+
+/*member: createB2:OutputUnit(6, {libC})*/
+createB2() => new lib.B2();
+
+/*member: createC3:OutputUnit(6, {libC})*/
+createC3() => new lib.C3();
+
+/*member: createD3:OutputUnit(6, {libC})*/
+createD3() => new lib.D3();
+
+/*member: createDooFunFunFoo:OutputUnit(6, {libC})*/
+createDooFunFunFoo() => lib.createDooFunFunFoo();
diff --git a/pkg/compiler/test/deferred_loading/data/lazy_types/main.dart b/pkg/compiler/test/deferred_loading/data/lazy_types/main.dart
new file mode 100644
index 0000000..885e32e
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/lazy_types/main.dart
@@ -0,0 +1,37 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'liba.dart' deferred as libA;
+import 'libb.dart' deferred as libB;
+import 'libc.dart' deferred as libC;
+
+/*member: foo:OutputUnit(main, {}),constants=[FunctionConstant(callFooMethod)=OutputUnit(3, {libB}),FunctionConstant(createB2)=OutputUnit(6, {libC}),FunctionConstant(createC3)=OutputUnit(6, {libC}),FunctionConstant(createD3)=OutputUnit(6, {libC}),FunctionConstant(createDooFunFunFoo)=OutputUnit(6, {libC}),FunctionConstant(isDooFunFunFoo)=OutputUnit(3, {libB}),FunctionConstant(isFoo)=OutputUnit(3, {libB}),FunctionConstant(isFoo)=OutputUnit(5, {libA}),FunctionConstant(isFoo)=OutputUnit(6, {libC}),FunctionConstant(isFunFunFoo)=OutputUnit(3, {libB}),FunctionConstant(isFunFunFoo)=OutputUnit(5, {libA}),FunctionConstant(isFunFunFoo)=OutputUnit(6, {libC}),FunctionConstant(isMega)=OutputUnit(5, {libA})]*/
+void foo() async {
+ await libA.loadLibrary();
+ await libB.loadLibrary();
+ await libC.loadLibrary();
+ print((libA.isFoo)(null as dynamic));
+ print((libA.isFunFunFoo)(null as dynamic));
+ print((libA.isFoo)(null as dynamic));
+ print((libA.isMega)(null as dynamic));
+
+ print((libB.isFoo)(null as dynamic));
+ print((libB.callFooMethod)());
+ print((libB.isFunFunFoo)(null as dynamic));
+ print((libB.isDooFunFunFoo)(null as dynamic));
+
+ print((libC.isFoo)(null as dynamic));
+ print((libC.isFunFunFoo)(null as dynamic));
+ print((libC.createB2)());
+ print((libC.createC3)());
+ print((libC.createD3)());
+ print((libC.createDooFunFunFoo)());
+}
+
+/*member: main:OutputUnit(main, {})*/
+main() {
+ foo();
+}
diff --git a/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/lib.dart b/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/lib.dart
new file mode 100644
index 0000000..0379450
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/lib.dart
@@ -0,0 +1,39 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+// All of these types are considered instantiated because we create an instance
+// of [C].
+
+/*class: A:OutputUnit(1, {lib})*/
+/*member: A.:OutputUnit(1, {lib})*/
+class A {}
+
+/*class: Box:OutputUnit(1, {lib})*/
+/*member: Box.:OutputUnit(1, {lib})*/
+class Box<T> {
+ /*member: Box.value:OutputUnit(1, {lib})*/
+ int value;
+}
+
+/*class: B:OutputUnit(1, {lib})*/
+/*member: B.:OutputUnit(1, {lib})*/
+class B<T> extends A {
+ /*member: B.box:OutputUnit(1, {lib})*/
+ final box = new Box<T>();
+}
+
+/*class: C:OutputUnit(1, {lib})*/
+/*member: C.:OutputUnit(1, {lib})*/
+class C extends B<N> {}
+
+// N is not instantiated, but used as a type argument in C and indirectly in a
+// Box<N>.
+// If we don't mark it as part of the output unit of C, we accidentally add it
+// to the main output unit. However, A is in the output unit of C so we fail
+// when trying to finalize the declaration of N while loading the main output
+// unit.
+/*class: N:OutputUnit(1, {lib})*/
+class N extends A {}
diff --git a/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/main.dart b/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/main.dart
new file mode 100644
index 0000000..0f072de
--- /dev/null
+++ b/pkg/compiler/test/deferred_loading/data/uninstantiated_type_variable/main.dart
@@ -0,0 +1,23 @@
+// Copyright (c) 2020, 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.
+
+// @dart = 2.7
+
+import 'lib.dart' deferred as lib;
+
+/// Regression test: if a type variable is used, but not instantiated, it still
+/// needs to be mapped to the deferred unit where it is used.
+///
+/// If not, we may include it in the main unit and may not see that the base
+/// class is not added to the main unit.
+/*member: main:OutputUnit(main, {})*/
+main() {
+ lib.loadLibrary().then(/*OutputUnit(main, {})*/ (_) {
+ dontInline(new lib.C()).box.value;
+ });
+}
+
+@pragma('dart2js:noInline')
+/*member: dontInline:OutputUnit(main, {})*/
+dontInline(x) => x;
diff --git a/pkg/compiler/test/model/native_test.dart b/pkg/compiler/test/model/native_test.dart
index 88d5340..418bf59 100644
--- a/pkg/compiler/test/model/native_test.dart
+++ b/pkg/compiler/test/model/native_test.dart
@@ -138,8 +138,8 @@
'54',
]);
- await runTest('tests/dart2js_2/native/native_test.dart',
- 'tests/dart2js_2/native/', {
+ await runTest(
+ 'tests/dart2js_2/native/native_test.dart', 'tests/dart2js_2/native/', {
'Class': Kind.regular,
'NativeClass': Kind.native,
'topLevelField': Kind.regular,
@@ -226,7 +226,10 @@
subTest.lines[lineIndex] = line;
int commentIndex = prefix.indexOf('// ');
if (commentIndex != -1) {
- subTest.expectedError = prefix.substring(commentIndex + 3).trim();
+ String combinedErrors = prefix.substring(commentIndex + 3);
+ for (String error in combinedErrors.split(',')) {
+ subTest.expectedErrors.add(error.trim());
+ }
}
commonLines.add('');
} else {
@@ -325,17 +328,20 @@
entryPoint: entryPoint,
memorySourceFiles: sources,
diagnosticHandler: collector);
- Expect.isFalse(result.isSuccess, "Expected compile time error for\n$subTest");
- Expect.equals(
- 1, collector.errors.length, "Expected compile time error for\n$subTest");
- Expect.equals(
- 'MessageKind.${subTest.expectedError}',
- collector.errors.first.messageKind.toString(),
- "Unexpected compile time error for\n$subTest");
+ Expect.isFalse(result.isSuccess,
+ "Expected compile time error(s) for\n$subTest");
+ List<String> expected =
+ subTest.expectedErrors.map((error) => 'MessageKind.' + error).toList();
+ List<String> actual =
+ collector.errors.map((error) => error.messageKind.toString()).toList();
+ expected.sort();
+ actual.sort();
+ Expect.listEquals(expected, actual,
+ "Unexpected compile time error(s) for\n$subTest");
}
class SubTest {
- String expectedError;
+ List<String> expectedErrors = [];
final Map<int, String> lines = <int, String>{};
String generateCode(List<String> commonLines) {
diff --git a/pkg/dartdev/lib/src/commands/run.dart b/pkg/dartdev/lib/src/commands/run.dart
index c6333f5..301068b 100644
--- a/pkg/dartdev/lib/src/commands/run.dart
+++ b/pkg/dartdev/lib/src/commands/run.dart
@@ -26,7 +26,10 @@
// provided before any command and to provide a more consistent help message
// with the rest of the tool.
@override
- final ArgParser argParser = ArgParser();
+ final ArgParser argParser = ArgParser(
+ // Don't parse flags after script name.
+ allowTrailingOptions: false,
+ );
@override
final bool verbose;
diff --git a/pkg/dartdev/pubspec.yaml b/pkg/dartdev/pubspec.yaml
index 061f6fa..a1e7fe2 100644
--- a/pkg/dartdev/pubspec.yaml
+++ b/pkg/dartdev/pubspec.yaml
@@ -7,7 +7,7 @@
sdk: '>=2.6.0 <3.0.0'
dependencies:
args: ^1.6.0
- cli_util: ^0.1.4
+ cli_util: '>=0.1.4 <0.3.0'
dart2native:
path: ../dart2native
dds:
diff --git a/pkg/dartdev/test/commands/run_test.dart b/pkg/dartdev/test/commands/run_test.dart
index ba7d746..38c40c1 100644
--- a/pkg/dartdev/test/commands/run_test.dart
+++ b/pkg/dartdev/test/commands/run_test.dart
@@ -108,12 +108,12 @@
final result = p.runSync('run', [
'--enable-experiment=non-nullable',
name,
- 'argument1',
+ '--argument1',
'argument2',
]);
// --enable-experiment and main.dart should not be passed.
- expect(result.stdout, equals('[argument1, argument2]\n'));
+ expect(result.stdout, equals('[--argument1, argument2]\n'));
expect(result.stderr, isEmpty);
expect(result.exitCode, 0);
});
@@ -126,12 +126,12 @@
final result = p.runSync('run', [
'--enable-experiment=non-nullable',
Uri.file(name).toString(),
- 'argument1',
+ '--argument1',
'argument2',
]);
// --enable-experiment and main.dart should not be passed.
- expect(result.stdout, equals('[argument1, argument2]\n'));
+ expect(result.stdout, equals('[--argument1, argument2]\n'));
expect(result.stderr, isEmpty);
expect(result.exitCode, 0);
});
diff --git a/pkg/dartfix/pubspec.yaml b/pkg/dartfix/pubspec.yaml
index ca488e6..8f39796 100644
--- a/pkg/dartfix/pubspec.yaml
+++ b/pkg/dartfix/pubspec.yaml
@@ -16,7 +16,7 @@
# protocol is experimental and will continue to evolve.
analysis_server_client: '>=1.1.3 <1.1.4'
args: ^1.4.0
- cli_util: ^0.1.3
+ cli_util: ^0.2.0
path: ^1.7.0
pub_semver: ^1.4.4
diff --git a/pkg/dartfix/test/src/migrate_command_test.dart b/pkg/dartfix/test/src/migrate_command_test.dart
index 4215266..a2fcf89 100644
--- a/pkg/dartfix/test/src/migrate_command_test.dart
+++ b/pkg/dartfix/test/src/migrate_command_test.dart
@@ -169,6 +169,16 @@
}
@override
+ void write(String message) {
+ stdoutBuffer.write(message);
+ }
+
+ @override
+ void writeCharCode(int charCode) {
+ stdoutBuffer.writeCharCode(charCode);
+ }
+
+ @override
void stderr(String message) {
stderrBuffer.writeln(message);
}
diff --git a/pkg/dartfix/test/src/test_context.dart b/pkg/dartfix/test/src/test_context.dart
index be43d3f..9e55c3f 100644
--- a/pkg/dartfix/test/src/test_context.dart
+++ b/pkg/dartfix/test/src/test_context.dart
@@ -67,6 +67,16 @@
}
@override
+ void write(String message) {
+ stdoutBuffer.write(message);
+ }
+
+ @override
+ void writeCharCode(int charCode) {
+ stdoutBuffer.writeCharCode(charCode);
+ }
+
+ @override
void trace(String message) {
if (debug) {
stdoutBuffer.writeln(message);
diff --git a/pkg/front_end/lib/src/fasta/builder/field_builder.dart b/pkg/front_end/lib/src/fasta/builder/field_builder.dart
index cbb624a..cbcc354 100644
--- a/pkg/front_end/lib/src/fasta/builder/field_builder.dart
+++ b/pkg/front_end/lib/src/fasta/builder/field_builder.dart
@@ -1410,7 +1410,7 @@
_getter
..isStatic = !isInstanceMember
..isExtensionMember = isExtensionMember
- ..isAbstract = isAbstract
+ ..isAbstract = isAbstract && !isExternal
..isExternal = isExternal;
// TODO(johnniwinther): How can the name already have been computed?
_getter.name ??= new Name(getterName, libraryBuilder.library);
@@ -1428,7 +1428,7 @@
_setter
..isStatic = !isInstanceMember
..isExtensionMember = isExtensionMember
- ..isAbstract = isAbstract
+ ..isAbstract = isAbstract && !isExternal
..isExternal = isExternal;
// TODO(johnniwinther): How can the name already have been computed?
_setter?.name ??= new Name(setterName, libraryBuilder.library);
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 49d7a0b..d7755a4 100644
--- a/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/constant_evaluator.dart
@@ -2302,6 +2302,14 @@
if (a.value.isNaN && b.value.isNaN) return falseConstant;
if (a.value == 0.0 && b.value == 0.0) return trueConstant;
}
+
+ if (a is DoubleConstant && b is IntConstant) {
+ return makeBoolConstant(a.value == b.value);
+ }
+
+ if (a is IntConstant && b is DoubleConstant) {
+ return makeBoolConstant(a.value == b.value);
+ }
return null;
}
diff --git a/pkg/front_end/lib/src/fasta/modifier.dart b/pkg/front_end/lib/src/fasta/modifier.dart
index 0d6a2b1..c93ef12 100644
--- a/pkg/front_end/lib/src/fasta/modifier.dart
+++ b/pkg/front_end/lib/src/fasta/modifier.dart
@@ -51,7 +51,7 @@
const int declaresConstConstructorMask = initializingFormalMask << 1;
/// Not a real modifier, and by setting it to zero, it is automatically ignored
-/// by [Modifier.validate] below.
+/// by [Modifier.toMask] below.
const int varMask = 0;
const Modifier Abstract = const Modifier(ModifierEnum.Abstract, abstractMask);
@@ -90,10 +90,8 @@
toString() => "modifier(${'$kind'.substring('ModifierEnum.'.length)})";
- static int validate(List<Modifier> modifiers, {bool isAbstract: false}) {
- // TODO(ahe): Rename this method, validation is now taken care of by the
- // parser.
- int result = isAbstract ? abstractMask : 0;
+ static int toMask(List<Modifier> modifiers) {
+ int result = 0;
if (modifiers == null) return result;
for (Modifier modifier in modifiers) {
result |= modifier.mask;
@@ -108,4 +106,13 @@
if (identical('var', lexeme)) return Var.mask;
return unhandled(lexeme, "Modifier.validateVarFinalOrConst", -1, null);
}
+
+ /// Returns [modifier] with [abstractMask] added if [isAbstract] and
+ /// [modifiers] doesn't contain [externalMask].
+ static int addAbstractMask(int modifiers, {bool isAbstract: false}) {
+ if (isAbstract && (modifiers & externalMask) == 0) {
+ modifiers |= abstractMask;
+ }
+ return modifiers;
+ }
}
diff --git a/pkg/front_end/lib/src/fasta/source/outline_builder.dart b/pkg/front_end/lib/src/fasta/source/outline_builder.dart
index 53b4729..7fa2286 100644
--- a/pkg/front_end/lib/src/fasta/source/outline_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/outline_builder.dart
@@ -813,9 +813,7 @@
}
}
int modifiers = pop();
- if (isAbstract) {
- modifiers |= abstractMask;
- }
+ modifiers = Modifier.addAbstractMask(modifiers, isAbstract: isAbstract);
if (nativeMethodName != null) {
modifiers |= externalMask;
}
@@ -1059,13 +1057,11 @@
isAbstract = false;
}
}
- int modifiers = Modifier.validate(pop(), isAbstract: isAbstract);
+ int modifiers = Modifier.toMask(pop());
+ modifiers = Modifier.addAbstractMask(modifiers, isAbstract: isAbstract);
if (nativeMethodName != null) {
modifiers |= externalMask;
}
- if ((modifiers & externalMask) != 0) {
- modifiers &= ~abstractMask;
- }
bool isConst = (modifiers & constMask) != 0;
int varFinalOrConstOffset = pop();
List<MetadataBuilder> metadata = pop();
diff --git a/pkg/front_end/messages.status b/pkg/front_end/messages.status
index 6459cc1..e375f71 100644
--- a/pkg/front_end/messages.status
+++ b/pkg/front_end/messages.status
@@ -441,6 +441,8 @@
InvalidVoid/script2: Fail
JsInteropAnonymousFactoryPositionalParameters/analyzerCode: Fail # Web compiler specific
JsInteropAnonymousFactoryPositionalParameters/example: Fail # Web compiler specific
+JsInteropEnclosingClassJSAnnotation/analyzerCode: Fail # Web compiler specific
+JsInteropEnclosingClassJSAnnotation/example: Fail # Web compiler specific
JsInteropIndexNotSupported/analyzerCode: Fail # Web compiler specific
JsInteropIndexNotSupported/example: Fail # Web compiler specific
JsInteropNamedParameters/analyzerCode: Fail # Web compiler specific
diff --git a/pkg/front_end/messages.yaml b/pkg/front_end/messages.yaml
index 62ae4a3..f317340 100644
--- a/pkg/front_end/messages.yaml
+++ b/pkg/front_end/messages.yaml
@@ -4090,6 +4090,14 @@
template: "Factory constructors for @anonymous JS interop classes should not contain any positional parameters."
tip: "Try replacing them with named parameters instead."
+JsInteropEnclosingClassJSAnnotation:
+ template: "Member has a JS interop annotation but the enclosing class does not."
+ tip: "Try adding the annotation to the enclosing class."
+
+JsInteropEnclosingClassJSAnnotationContext:
+ template: "This is the enclosing class."
+ severity: CONTEXT
+
JsInteropIndexNotSupported:
template: "JS interop classes do not support [] and []= operator methods."
tip: "Try replacing with a normal method."
diff --git a/pkg/front_end/test/crashing_test_case_minimizer.dart b/pkg/front_end/test/crashing_test_case_minimizer.dart
index 425e5c2..c6aca7f 100644
--- a/pkg/front_end/test/crashing_test_case_minimizer.dart
+++ b/pkg/front_end/test/crashing_test_case_minimizer.dart
@@ -20,6 +20,9 @@
import 'package:front_end/src/api_prototype/compiler_options.dart'
show CompilerOptions, DiagnosticMessage;
+import 'package:front_end/src/api_prototype/experimental_flags.dart'
+ show ExperimentalFlag;
+
import 'package:front_end/src/api_prototype/file_system.dart'
show FileSystem, FileSystemEntity, FileSystemException;
@@ -546,6 +549,10 @@
CompilerContext setupCompilerContext() {
CompilerOptions options = getOptions();
+ if (nnbd) {
+ options.experimentalFlags = {ExperimentalFlag.nonNullable: true};
+ }
+
TargetFlags targetFlags = new TargetFlags(
enableNullSafety: nnbd, trackWidgetCreation: widgetTransformation);
Target target;
diff --git a/pkg/front_end/testcases/general/external_method.dart b/pkg/front_end/testcases/general/external_method.dart
new file mode 100644
index 0000000..976d23b
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2020, 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.
+
+external void externalMethod();
+
+class Class {
+ external void externalMethod();
+}
+
+void main() {}
diff --git a/pkg/front_end/testcases/general/external_method.dart.outline.expect b/pkg/front_end/testcases/general/external_method.dart.outline.expect
new file mode 100644
index 0000000..b9975e3
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart.outline.expect
@@ -0,0 +1,22 @@
+library;
+import self as self;
+import "dart:core" as core;
+
+class Class extends core::Object {
+ synthetic constructor •() → self::Class*
+ ;
+ external method externalMethod() → void;
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
+external static method externalMethod() → void;
+static method main() → void
+ ;
diff --git a/pkg/front_end/testcases/general/external_method.dart.strong.expect b/pkg/front_end/testcases/general/external_method.dart.strong.expect
new file mode 100644
index 0000000..1fed66d
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart.strong.expect
@@ -0,0 +1,22 @@
+library;
+import self as self;
+import "dart:core" as core;
+
+class Class extends core::Object {
+ synthetic constructor •() → self::Class*
+ : super core::Object::•()
+ ;
+ external method externalMethod() → void;
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
+external static method externalMethod() → void;
+static method main() → void {}
diff --git a/pkg/front_end/testcases/general/external_method.dart.strong.transformed.expect b/pkg/front_end/testcases/general/external_method.dart.strong.transformed.expect
new file mode 100644
index 0000000..1fed66d
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart.strong.transformed.expect
@@ -0,0 +1,22 @@
+library;
+import self as self;
+import "dart:core" as core;
+
+class Class extends core::Object {
+ synthetic constructor •() → self::Class*
+ : super core::Object::•()
+ ;
+ external method externalMethod() → void;
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
+external static method externalMethod() → void;
+static method main() → void {}
diff --git a/pkg/front_end/testcases/general/external_method.dart.textual_outline.expect b/pkg/front_end/testcases/general/external_method.dart.textual_outline.expect
new file mode 100644
index 0000000..a36e380
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart.textual_outline.expect
@@ -0,0 +1,7 @@
+external void externalMethod();
+
+class Class {
+ external void externalMethod();
+}
+
+void main() {}
diff --git a/pkg/front_end/testcases/general/external_method.dart.textual_outline_modelled.expect b/pkg/front_end/testcases/general/external_method.dart.textual_outline_modelled.expect
new file mode 100644
index 0000000..b902ad8
--- /dev/null
+++ b/pkg/front_end/testcases/general/external_method.dart.textual_outline_modelled.expect
@@ -0,0 +1,6 @@
+class Class {
+ external void externalMethod();
+}
+
+external void externalMethod();
+void main() {}
diff --git a/pkg/front_end/testcases/general/micro.dart.outline.expect b/pkg/front_end/testcases/general/micro.dart.outline.expect
index 110be54..7f70142 100644
--- a/pkg/front_end/testcases/general/micro.dart.outline.expect
+++ b/pkg/front_end/testcases/general/micro.dart.outline.expect
@@ -115,8 +115,8 @@
}
static method staticMethod() → dynamic
;
-external static abstract method externalStatic() → core::bool*;
-external static abstract method createBar() → self::Bar*;
+external static method externalStatic() → core::bool*;
+external static method createBar() → self::Bar*;
static method stringArgument(dynamic x) → dynamic
;
static method intArgument(dynamic x) → dynamic
diff --git a/pkg/front_end/testcases/general/micro.dart.strong.expect b/pkg/front_end/testcases/general/micro.dart.strong.expect
index 5170680..302f493 100644
--- a/pkg/front_end/testcases/general/micro.dart.strong.expect
+++ b/pkg/front_end/testcases/general/micro.dart.strong.expect
@@ -123,8 +123,8 @@
static method staticMethod() → dynamic {
return "sdfg";
}
-external static abstract method externalStatic() → core::bool*;
-external static abstract method createBar() → self::Bar*;
+external static method externalStatic() → core::bool*;
+external static method createBar() → self::Bar*;
static method stringArgument(dynamic x) → dynamic {}
static method intArgument(dynamic x) → dynamic {}
static method makeDynamicCall(dynamic receiver) → void {
diff --git a/pkg/front_end/testcases/general/micro.dart.strong.transformed.expect b/pkg/front_end/testcases/general/micro.dart.strong.transformed.expect
index 5170680..302f493 100644
--- a/pkg/front_end/testcases/general/micro.dart.strong.transformed.expect
+++ b/pkg/front_end/testcases/general/micro.dart.strong.transformed.expect
@@ -123,8 +123,8 @@
static method staticMethod() → dynamic {
return "sdfg";
}
-external static abstract method externalStatic() → core::bool*;
-external static abstract method createBar() → self::Bar*;
+external static method externalStatic() → core::bool*;
+external static method createBar() → self::Bar*;
static method stringArgument(dynamic x) → dynamic {}
static method intArgument(dynamic x) → dynamic {}
static method makeDynamicCall(dynamic receiver) → void {
diff --git a/pkg/front_end/testcases/general/optional.dart.outline.expect b/pkg/front_end/testcases/general/optional.dart.outline.expect
index fc765ff..7960d64 100644
--- a/pkg/front_end/testcases/general/optional.dart.outline.expect
+++ b/pkg/front_end/testcases/general/optional.dart.outline.expect
@@ -77,6 +77,6 @@
abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
abstract member-signature get runtimeType() → core::Type*;
}
-external static abstract method createExternal() → self::External*;
+external static method createExternal() → self::External*;
static method main() → dynamic
;
diff --git a/pkg/front_end/testcases/general/optional.dart.strong.expect b/pkg/front_end/testcases/general/optional.dart.strong.expect
index 699fb55..fdbfad7 100644
--- a/pkg/front_end/testcases/general/optional.dart.strong.expect
+++ b/pkg/front_end/testcases/general/optional.dart.strong.expect
@@ -108,7 +108,7 @@
abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
abstract member-signature get runtimeType() → core::Type*;
}
-external static abstract method createExternal() → self::External*;
+external static method createExternal() → self::External*;
static method main() → dynamic {
self::Foo* foo = new self::Foo::•();
dynamic string1 = foo.{self::Foo::method}(1);
diff --git a/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.expect b/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.expect
index 5170680..302f493 100644
--- a/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.expect
+++ b/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.expect
@@ -123,8 +123,8 @@
static method staticMethod() → dynamic {
return "sdfg";
}
-external static abstract method externalStatic() → core::bool*;
-external static abstract method createBar() → self::Bar*;
+external static method externalStatic() → core::bool*;
+external static method createBar() → self::Bar*;
static method stringArgument(dynamic x) → dynamic {}
static method intArgument(dynamic x) → dynamic {}
static method makeDynamicCall(dynamic receiver) → void {
diff --git a/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.transformed.expect b/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.transformed.expect
index 5170680..302f493 100644
--- a/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/general_nnbd_opt_out/micro.dart.weak.transformed.expect
@@ -123,8 +123,8 @@
static method staticMethod() → dynamic {
return "sdfg";
}
-external static abstract method externalStatic() → core::bool*;
-external static abstract method createBar() → self::Bar*;
+external static method externalStatic() → core::bool*;
+external static method createBar() → self::Bar*;
static method stringArgument(dynamic x) → dynamic {}
static method intArgument(dynamic x) → dynamic {}
static method makeDynamicCall(dynamic receiver) → void {
diff --git a/pkg/front_end/testcases/general_nnbd_opt_out/optional.dart.weak.expect b/pkg/front_end/testcases/general_nnbd_opt_out/optional.dart.weak.expect
index 6e7a5a8..79679d1 100644
--- a/pkg/front_end/testcases/general_nnbd_opt_out/optional.dart.weak.expect
+++ b/pkg/front_end/testcases/general_nnbd_opt_out/optional.dart.weak.expect
@@ -108,7 +108,7 @@
abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
abstract member-signature get runtimeType() → core::Type*;
}
-external static abstract method createExternal() → self::External*;
+external static method createExternal() → self::External*;
static method main() → dynamic {
self::Foo* foo = new self::Foo::•();
dynamic string1 = foo.{self::Foo::method}(1);
diff --git a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.outline.expect b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.outline.expect
index 0f64f8f..4ac62a9 100644
--- a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.outline.expect
+++ b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.outline.expect
@@ -193,22 +193,22 @@
abstract set initializedField1(core::int #t2) → void;
abstract get initializedField2() → core::int;
abstract set initializedField2(core::int #t3) → void;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t4) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t5) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t4) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t5) → void;
external get externalLateInstanceField() → core::int;
external set externalLateInstanceField(core::int #t6) → void;
}
abstract class B extends core::Object /*isMixinDeclaration*/ {
static field core::int staticField;
static final field core::int finalStaticField;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t7) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t8) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t7) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t8) → void;
}
extension Extension on self::A {
get extensionInstanceField = get self::Extension|extensionInstanceField;
diff --git a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.expect b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.expect
index 002cc9d..8181af4 100644
--- a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.expect
+++ b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.expect
@@ -225,22 +225,22 @@
abstract set initializedField1(core::int #t4) → void;
abstract get initializedField2() → core::int;
abstract set initializedField2(core::int #t5) → void;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t6) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t7) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t6) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t7) → void;
external get externalLateInstanceField() → core::int;
external set externalLateInstanceField(core::int #t8) → void;
}
abstract class B extends core::Object /*isMixinDeclaration*/ {
static field core::int staticField = null;
static final field core::int finalStaticField = null;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t9) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t10) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t9) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t10) → void;
}
extension Extension on self::A {
get extensionInstanceField = get self::Extension|extensionInstanceField;
diff --git a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.transformed.expect b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.transformed.expect
index 002cc9d..8181af4 100644
--- a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.strong.transformed.expect
@@ -225,22 +225,22 @@
abstract set initializedField1(core::int #t4) → void;
abstract get initializedField2() → core::int;
abstract set initializedField2(core::int #t5) → void;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t6) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t7) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t6) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t7) → void;
external get externalLateInstanceField() → core::int;
external set externalLateInstanceField(core::int #t8) → void;
}
abstract class B extends core::Object /*isMixinDeclaration*/ {
static field core::int staticField = null;
static final field core::int finalStaticField = null;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t9) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t10) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t9) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t10) → void;
}
extension Extension on self::A {
get extensionInstanceField = get self::Extension|extensionInstanceField;
diff --git a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.expect b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.expect
index 002cc9d..8181af4 100644
--- a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.expect
+++ b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.expect
@@ -225,22 +225,22 @@
abstract set initializedField1(core::int #t4) → void;
abstract get initializedField2() → core::int;
abstract set initializedField2(core::int #t5) → void;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t6) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t7) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t6) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t7) → void;
external get externalLateInstanceField() → core::int;
external set externalLateInstanceField(core::int #t8) → void;
}
abstract class B extends core::Object /*isMixinDeclaration*/ {
static field core::int staticField = null;
static final field core::int finalStaticField = null;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t9) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t10) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t9) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t10) → void;
}
extension Extension on self::A {
get extensionInstanceField = get self::Extension|extensionInstanceField;
diff --git a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.transformed.expect b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.transformed.expect
index 002cc9d..8181af4 100644
--- a/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.transformed.expect
+++ b/pkg/front_end/testcases/nnbd/abstract_field_errors.dart.weak.transformed.expect
@@ -225,22 +225,22 @@
abstract set initializedField1(core::int #t4) → void;
abstract get initializedField2() → core::int;
abstract set initializedField2(core::int #t5) → void;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t6) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t7) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t6) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t7) → void;
external get externalLateInstanceField() → core::int;
external set externalLateInstanceField(core::int #t8) → void;
}
abstract class B extends core::Object /*isMixinDeclaration*/ {
static field core::int staticField = null;
static final field core::int finalStaticField = null;
- external abstract get externalInstanceField() → core::int;
- external abstract set externalInstanceField(core::int #t9) → void;
- external abstract get externalFinalInstanceField() → core::int;
- external abstract get externalCovariantInstanceField() → core::num;
- external abstract set externalCovariantInstanceField(covariant core::num #t10) → void;
+ external get externalInstanceField() → core::int;
+ external set externalInstanceField(core::int #t9) → void;
+ external get externalFinalInstanceField() → core::int;
+ external get externalCovariantInstanceField() → core::num;
+ external set externalCovariantInstanceField(covariant core::num #t10) → void;
}
extension Extension on self::A {
get extensionInstanceField = get self::Extension|extensionInstanceField;
diff --git a/pkg/front_end/testcases/nnbd/platform_definite_assignment/main.dart.outline.expect b/pkg/front_end/testcases/nnbd/platform_definite_assignment/main.dart.outline.expect
index f734994..1d570f5 100644
--- a/pkg/front_end/testcases/nnbd/platform_definite_assignment/main.dart.outline.expect
+++ b/pkg/front_end/testcases/nnbd/platform_definite_assignment/main.dart.outline.expect
@@ -35,6 +35,6 @@
static method method(core::int a) → core::int
;
@_in::patch
-external static abstract method patchedMethod(core::int a) → void;
+external static method patchedMethod(core::int a) → void;
static method /* from org-dartlang-testcase:///patch_lib.dart */ _injectedMethod(core::int i) → core::int
;
diff --git a/pkg/front_end/testcases/nnbd/platform_optional_parameters/main.dart.outline.expect b/pkg/front_end/testcases/nnbd/platform_optional_parameters/main.dart.outline.expect
index 25d8360..85646dd 100644
--- a/pkg/front_end/testcases/nnbd/platform_optional_parameters/main.dart.outline.expect
+++ b/pkg/front_end/testcases/nnbd/platform_optional_parameters/main.dart.outline.expect
@@ -58,6 +58,6 @@
static method method([core::int i]) → void
;
@_in::patch
-external static abstract method patchedMethod([core::int i]) → void;
+external static method patchedMethod([core::int i]) → void;
static method /* from org-dartlang-testcase:///patch_lib.dart */ _injectedMethod([core::int i]) → void
;
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart
new file mode 100644
index 0000000..3e5c10c
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart
@@ -0,0 +1,8 @@
+import 'flutter_issue_63029_lib1.dart';
+import 'flutter_issue_63029_lib2.dart';
+
+class E extends A {}
+
+class F extends B<E> with D<E> {}
+
+main() {}
\ No newline at end of file
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline.expect b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline.expect
new file mode 100644
index 0000000..2c99d44
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline.expect
@@ -0,0 +1,8 @@
+import 'flutter_issue_63029_lib1.dart';
+import 'flutter_issue_63029_lib2.dart';
+
+class E extends A {}
+
+class F extends B<E> with D<E> {}
+
+main() {}
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline_modelled.expect b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline_modelled.expect
new file mode 100644
index 0000000..2c99d44
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.textual_outline_modelled.expect
@@ -0,0 +1,8 @@
+import 'flutter_issue_63029_lib1.dart';
+import 'flutter_issue_63029_lib2.dart';
+
+class E extends A {}
+
+class F extends B<E> with D<E> {}
+
+main() {}
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.expect b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.expect
new file mode 100644
index 0000000..e8fe043
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.expect
@@ -0,0 +1,87 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart:6:7: Error: 'B<E>' doesn't implement 'B<E>' so it can't be used with 'D<E>'.
+// - 'B' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib1.dart'.
+// - 'E' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart'.
+// - 'D' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib2.dart'.
+// class F extends B<E> with D<E> {}
+// ^
+//
+import self as self;
+import "flutter_issue_63029_lib1.dart" as flu;
+import "flutter_issue_63029_lib2.dart" as flu2;
+import "dart:core" as core;
+
+import "org-dartlang-testcase:///flutter_issue_63029_lib1.dart";
+import "org-dartlang-testcase:///flutter_issue_63029_lib2.dart";
+
+class E extends flu::A {
+ synthetic constructor •() → self::E
+ : super flu::A::•()
+ ;
+}
+abstract class _F&B&D = flu::B<self::E> with flu2::D<self::E> /*isAnonymousMixin*/ {
+ synthetic constructor •() → self::_F&B&D
+ : super flu::B::•()
+ ;
+ abstract forwarding-stub operator ==(dynamic other) → core::bool*;
+}
+class F extends self::_F&B&D {
+ synthetic constructor •() → self::F
+ : super self::_F&B&D::•()
+ ;
+ abstract forwarding-stub operator ==(dynamic other) → core::bool*;
+}
+static method main() → dynamic {}
+
+library /*isNonNullableByDefault*/;
+import self as flu;
+import "dart:core" as core;
+
+abstract class A extends core::Object {
+ synthetic constructor •() → flu::A
+ : super core::Object::•()
+ ;
+}
+abstract class B<T extends flu::A = flu::A> extends core::Object {
+ synthetic constructor •() → flu::B<flu::B::T>
+ : super core::Object::•()
+ ;
+}
+
+library;
+import self as flu2;
+import "dart:core" as core;
+import "flutter_issue_63029_lib1.dart" as flu;
+
+import "org-dartlang-testcase:///flutter_issue_63029_lib1.dart";
+
+class C extends core::Object {
+ synthetic constructor •() → flu2::C*
+ : super core::Object::•()
+ ;
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
+abstract class D<T extends flu::A* = flu::A*> extends flu::B<flu2::D::T*> implements flu2::C /*isMixinDeclaration*/ {
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.transformed.expect b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.transformed.expect
new file mode 100644
index 0000000..f39dd6f
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart.weak.transformed.expect
@@ -0,0 +1,96 @@
+library /*isNonNullableByDefault*/;
+//
+// Problems in library:
+//
+// pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart:6:7: Error: 'B<E>' doesn't implement 'B<E>' so it can't be used with 'D<E>'.
+// - 'B' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib1.dart'.
+// - 'E' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029.dart'.
+// - 'D' is from 'pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib2.dart'.
+// class F extends B<E> with D<E> {}
+// ^
+//
+import self as self;
+import "flutter_issue_63029_lib1.dart" as flu;
+import "flutter_issue_63029_lib2.dart" as flu2;
+import "dart:core" as core;
+
+import "org-dartlang-testcase:///flutter_issue_63029_lib1.dart";
+import "org-dartlang-testcase:///flutter_issue_63029_lib2.dart";
+
+class E extends flu::A {
+ synthetic constructor •() → self::E
+ : super flu::A::•()
+ ;
+}
+abstract class _F&B&D extends flu::B<self::E> implements flu2::D<self::E> /*isAnonymousMixin,isEliminatedMixin*/ {
+ synthetic constructor •() → self::_F&B&D
+ : super flu::B::•()
+ ;
+ abstract member-signature operator /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ ==(dynamic other) → core::bool*;
+ abstract member-signature get /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ _identityHashCode() → core::int*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature get /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ hashCode() → core::int*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ toString() → core::String*;
+ abstract member-signature method /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get /*isNullableByDefault, from org-dartlang-testcase:///flutter_issue_63029_lib2.dart */ runtimeType() → core::Type*;
+}
+class F extends self::_F&B&D {
+ synthetic constructor •() → self::F
+ : super self::_F&B&D::•()
+ ;
+ abstract forwarding-stub operator ==(dynamic other) → core::bool*;
+}
+static method main() → dynamic {}
+
+library /*isNonNullableByDefault*/;
+import self as flu;
+import "dart:core" as core;
+
+abstract class A extends core::Object {
+ synthetic constructor •() → flu::A
+ : super core::Object::•()
+ ;
+}
+abstract class B<T extends flu::A = flu::A> extends core::Object {
+ synthetic constructor •() → flu::B<flu::B::T>
+ : super core::Object::•()
+ ;
+}
+
+library;
+import self as flu2;
+import "dart:core" as core;
+import "flutter_issue_63029_lib1.dart" as flu;
+
+import "org-dartlang-testcase:///flutter_issue_63029_lib1.dart";
+
+class C extends core::Object {
+ synthetic constructor •() → flu2::C*
+ : super core::Object::•()
+ ;
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
+abstract class D<T extends flu::A* = flu::A*> extends flu::B<flu2::D::T*> implements flu2::C /*isMixinDeclaration*/ {
+ abstract member-signature get _identityHashCode() → core::int*;
+ abstract member-signature method _instanceOf(dynamic instantiatorTypeArguments, dynamic functionTypeArguments, dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOf(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfTrue(dynamic type) → core::bool*;
+ abstract member-signature method _simpleInstanceOfFalse(dynamic type) → core::bool*;
+ abstract member-signature operator ==(dynamic other) → core::bool*;
+ abstract member-signature get hashCode() → core::int*;
+ abstract member-signature method toString() → core::String*;
+ abstract member-signature method noSuchMethod(core::Invocation* invocation) → dynamic;
+ abstract member-signature get runtimeType() → core::Type*;
+}
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib1.dart b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib1.dart
new file mode 100644
index 0000000..90bdb8f
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib1.dart
@@ -0,0 +1,3 @@
+abstract class A {}
+
+abstract class B<T extends A> {}
diff --git a/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib2.dart b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib2.dart
new file mode 100644
index 0000000..7205587
--- /dev/null
+++ b/pkg/front_end/testcases/nnbd_mixed/flutter_issue_63029/flutter_issue_63029_lib2.dart
@@ -0,0 +1,7 @@
+// @dart = 2.8
+
+import 'flutter_issue_63029_lib1.dart';
+
+class C {}
+
+mixin D<T extends A> on B<T> implements C {}
diff --git a/pkg/kernel/lib/verifier.dart b/pkg/kernel/lib/verifier.dart
index 4a5614a..c9238d3 100644
--- a/pkg/kernel/lib/verifier.dart
+++ b/pkg/kernel/lib/verifier.dart
@@ -293,6 +293,9 @@
currentMember = node;
var oldParent = enterParent(node);
classTypeParametersAreInScope = !node.isStatic;
+ if (node.isAbstract && node.isExternal) {
+ problem(node, "Procedure cannot be both abstract and external.");
+ }
node.function.accept(this);
classTypeParametersAreInScope = false;
visitList(node.annotations, this);
diff --git a/pkg/nnbd_migration/pubspec.yaml b/pkg/nnbd_migration/pubspec.yaml
index 2495d9c..dc1ee94 100644
--- a/pkg/nnbd_migration/pubspec.yaml
+++ b/pkg/nnbd_migration/pubspec.yaml
@@ -10,7 +10,7 @@
analyzer_plugin: ^0.2.4
args: ^1.4.4
charcode: ^1.1.2
- cli_util: ^0.1.4
+ cli_util: ^0.2.0
collection: ^1.14.11
crypto: ^2.0.6
meta: ^1.1.6
diff --git a/pkg/nnbd_migration/test/migration_cli_test.dart b/pkg/nnbd_migration/test/migration_cli_test.dart
index ce1f1e3..cc7894d 100644
--- a/pkg/nnbd_migration/test/migration_cli_test.dart
+++ b/pkg/nnbd_migration/test/migration_cli_test.dart
@@ -1850,6 +1850,16 @@
}
@override
+ void write(String message) {
+ stdoutBuffer.write(message);
+ }
+
+ @override
+ void writeCharCode(int charCode) {
+ stdoutBuffer.writeCharCode(charCode);
+ }
+
+ @override
void trace(String message) {
throw UnimplementedError('TODO(paulberry)');
}
diff --git a/pkg/test_runner/lib/src/command.dart b/pkg/test_runner/lib/src/command.dart
index 7ea9107..ec9eda3 100644
--- a/pkg/test_runner/lib/src/command.dart
+++ b/pkg/test_runner/lib/src/command.dart
@@ -340,24 +340,21 @@
}
class VMKernelCompilationCommand extends CompilationCommand {
- final List<String> batchArgs;
-
VMKernelCompilationCommand(
String outputFile,
List<Uri> bootstrapDependencies,
String executable,
List<String> arguments,
Map<String, String> environmentOverrides,
- this.batchArgs,
{bool alwaysCompile,
int index = 0})
- : super('vm_compile_to_kernel $batchArgs', outputFile,
- bootstrapDependencies, executable, arguments, environmentOverrides,
+ : super('vm_compile_to_kernel', outputFile, bootstrapDependencies,
+ executable, arguments, environmentOverrides,
alwaysCompile: alwaysCompile, index: index);
VMKernelCompilationCommand indexedCopy(int index) =>
VMKernelCompilationCommand(outputFile, _bootstrapDependencies, executable,
- arguments, environmentOverrides, batchArgs,
+ arguments, environmentOverrides,
alwaysCompile: _alwaysCompile, index: index);
VMKernelCompilationCommandOutput createOutput(
@@ -372,11 +369,6 @@
this, exitCode, timedOut, stdout, stderr, time, compilationSkipped);
int get maxNumRetries => 1;
-
- @override
- List<String> get batchArguments {
- return batchArgs;
- }
}
/// This is just a Pair(String, Map) class with hashCode and operator ==
diff --git a/pkg/test_runner/lib/src/compiler_configuration.dart b/pkg/test_runner/lib/src/compiler_configuration.dart
index b2425ea..e841c9d 100644
--- a/pkg/test_runner/lib/src/compiler_configuration.dart
+++ b/pkg/test_runner/lib/src/compiler_configuration.dart
@@ -1080,15 +1080,8 @@
var pkgVmDir = Platform.script.resolve('../../../pkg/vm').toFilePath();
var genKernel = '$pkgVmDir/tool/gen_kernel$shellScriptExtension';
- var useAbiVersion = arguments.firstWhere(
- (arg) => arg.startsWith('--use-abi-version='),
- orElse: () => null);
-
var kernelBinariesFolder = '${_configuration.buildDirectory}';
- if (useAbiVersion != null) {
- var version = useAbiVersion.split('=')[1];
- kernelBinariesFolder += '/dart-sdk/lib/_internal/abiversions/$version';
- } else if (_useSdk) {
+ if (_useSdk) {
kernelBinariesFolder += '/dart-sdk/lib/_internal';
}
@@ -1119,10 +1112,8 @@
..._configuration.genKernelOptions,
];
- var batchArgs = [if (useAbiVersion != null) useAbiVersion];
-
return VMKernelCompilationCommand(dillFile, bootstrapDependencies(),
- genKernel, args, environmentOverrides, batchArgs,
+ genKernel, args, environmentOverrides,
alwaysCompile: true);
}
}
diff --git a/pkg/test_runner/lib/src/fuchsia.dart b/pkg/test_runner/lib/src/fuchsia.dart
index 874ded5..182fe4b 100644
--- a/pkg/test_runner/lib/src/fuchsia.dart
+++ b/pkg/test_runner/lib/src/fuchsia.dart
@@ -28,11 +28,10 @@
Process _server;
String _deviceName;
- static Future<void> publishPackage(
- int emuCpus, String buildDir, String mode) async {
+ static Future<void> publishPackage(String buildDir, String mode) async {
if (_inst == null) {
_inst = FuchsiaEmulator();
- await _inst._start(emuCpus);
+ await _inst._start();
}
await _inst._publishPackage(buildDir, mode);
}
@@ -48,18 +47,11 @@
arg.replaceAll(Repository.uri.toFilePath(), '/pkg/data/')));
}
- Future<void> _start(int emuCpus) async {
+ Future<void> _start() async {
// Start the emulator.
- DebugLogger.info('Starting Fuchsia emulator with $emuCpus CPUs');
- _emu = await Process.start('xvfb-run', [
- femuTool,
- '--image',
- 'qemu-x64',
- '-N',
- '--headless',
- '-s',
- '$emuCpus'
- ]);
+ DebugLogger.info('Starting Fuchsia emulator');
+ _emu = await Process.start(
+ 'xvfb-run', [femuTool, '--image', 'qemu-x64', '-N', '--headless']);
// Wait until the emulator is ready and has a valid device name.
var deviceNameFuture = Completer<String>();
@@ -159,7 +151,7 @@
var result = await Process.run(fpubTool, [packageFile]);
if (result.exitCode != 0) {
_stop();
- _throwResult('Publishing package', result);
+ throw _formatFailedResult('Publishing package', result);
}
// Verify that the publication was successful by running hello_test.dart.
@@ -172,7 +164,7 @@
_getSshArgs(mode, ['/pkg/data/pkg/testing/test/hello_test.dart']));
if (result.exitCode != 0 || result.stdout != 'Hello, World!\n') {
_stop();
- _throwResult('Verifying publication', result);
+ throw _formatFailedResult('Verifying publication', result);
}
DebugLogger.info('Publication successful');
}
@@ -190,10 +182,12 @@
emulatorPidPattern.firstMatch(result.stdout as String)?.group(1) ??
"");
if (result.exitCode != 0 || emuPid == null) {
- _throwResult('Searching for emulator process', result);
+ DebugLogger.info(
+ _formatFailedResult('Searching for emulator process', result));
+ } else {
+ Process.killPid(emuPid);
+ DebugLogger.info('Fuchsia emulator stopped');
}
- Process.killPid(emuPid);
- DebugLogger.info('Fuchsia emulator stopped');
}
if (_server != null) {
@@ -205,9 +199,11 @@
// to manually kill this process, using fserve.sh again.
var result = Process.runSync(fserveTool, ['--kill']);
if (result.exitCode != 0) {
- _throwResult('Killing package manager', result);
+ DebugLogger.info(
+ _formatFailedResult('Killing package manager', result));
+ } else {
+ DebugLogger.info('Fuchsia package server stopped');
}
- DebugLogger.info('Fuchsia package server stopped');
}
}
@@ -218,8 +214,8 @@
return output;
}
- void _throwResult(String name, ProcessResult result) {
- throw '$name failed with exit code: ${result.exitCode}\n\n' +
+ String _formatFailedResult(String name, ProcessResult result) {
+ return '$name failed with exit code: ${result.exitCode}\n\n' +
_formatOutputs(result.stdout as String, result.stderr as String);
}
}
diff --git a/pkg/test_runner/lib/src/static_error.dart b/pkg/test_runner/lib/src/static_error.dart
index 23fd8f3..08104d7 100644
--- a/pkg/test_runner/lib/src/static_error.dart
+++ b/pkg/test_runner/lib/src/static_error.dart
@@ -55,6 +55,44 @@
class StaticError implements Comparable<StaticError> {
static const _unspecified = "unspecified";
+ /// The error codes for all of the analyzer errors that are non-fatal
+ /// warnings.
+ ///
+ /// We can't rely on the type ("STATIC_WARNING", etc.) because for historical
+ /// reasons the "warning" types contain a large number of actual compile
+ /// errors.
+ // TODO(rnystrom): This list was generated on 2020/07/24 based on the list
+ // of error codes in sdk/pkg/analyzer/lib/error/error.dart. Is there a more
+ // systematic way to handle this?
+ static const _analyzerWarningCodes = {
+ "STATIC_WARNING.ANALYSIS_OPTION_DEPRECATED",
+ "STATIC_WARNING.INCLUDE_FILE_NOT_FOUND",
+ "STATIC_WARNING.INCLUDED_FILE_WARNING",
+ "STATIC_WARNING.INVALID_OPTION",
+ "STATIC_WARNING.INVALID_SECTION_FORMAT",
+ "STATIC_WARNING.SPEC_MODE_REMOVED",
+ "STATIC_WARNING.UNRECOGNIZED_ERROR_CODE",
+ "STATIC_WARNING.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE",
+ "STATIC_WARNING.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES",
+ "STATIC_WARNING.UNSUPPORTED_OPTION_WITHOUT_VALUES",
+ "STATIC_WARNING.UNSUPPORTED_VALUE",
+ "STATIC_WARNING.CAMERA_PERMISSIONS_INCOMPATIBLE",
+ "STATIC_WARNING.NO_TOUCHSCREEN_FEATURE",
+ "STATIC_WARNING.NON_RESIZABLE_ACTIVITY",
+ "STATIC_WARNING.PERMISSION_IMPLIES_UNSUPPORTED_HARDWARE",
+ "STATIC_WARNING.SETTING_ORIENTATION_ON_ACTIVITY",
+ "STATIC_WARNING.UNSUPPORTED_CHROME_OS_FEATURE",
+ "STATIC_WARNING.UNSUPPORTED_CHROME_OS_HARDWARE",
+ "STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION",
+ "STATIC_WARNING.INVALID_NULL_AWARE_OPERATOR",
+ "STATIC_WARNING.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED",
+ "STATIC_WARNING.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL",
+ "STATIC_WARNING.MISSING_ENUM_CONSTANT_IN_SWITCH",
+ "STATIC_WARNING.UNNECESSARY_NON_NULL_ASSERTION",
+ "STATIC_WARNING.TOP_LEVEL_INSTANCE_GETTER",
+ "STATIC_WARNING.TOP_LEVEL_INSTANCE_METHOD",
+ };
+
/// Parses the set of static error expectations defined in the Dart source
/// file [source].
static List<StaticError> parseExpectations(String source) =>
@@ -296,6 +334,25 @@
return result;
}
+ /// Whether this error is only considered a warning on all front ends that
+ /// report it.
+ bool get isWarning {
+ var analyzer = _errors[ErrorSource.analyzer];
+ if (analyzer != null && !_analyzerWarningCodes.contains(analyzer)) {
+ return false;
+ }
+
+ // TODO(42787): Once CFE starts reporting warnings, encode that in the
+ // message somehow and then look for it here.
+ if (hasError(ErrorSource.cfe)) return false;
+
+ // TODO(rnystrom): If the web compilers report warnings, encode that in the
+ // message somehow and then look for it here.
+ if (hasError(ErrorSource.web)) return false;
+
+ return true;
+ }
+
String toString() {
var result = "Error at $location";
diff --git a/pkg/test_runner/lib/src/test_configurations.dart b/pkg/test_runner/lib/src/test_configurations.dart
index 32201e8..93de210 100644
--- a/pkg/test_runner/lib/src/test_configurations.dart
+++ b/pkg/test_runner/lib/src/test_configurations.dart
@@ -155,7 +155,7 @@
}
if (configuration.system == System.fuchsia) {
- await FuchsiaEmulator.publishPackage(configuration.taskCount,
+ await FuchsiaEmulator.publishPackage(
configuration.buildDirectory, configuration.mode.name);
}
}
diff --git a/pkg/test_runner/lib/src/test_file.dart b/pkg/test_runner/lib/src/test_file.dart
index 6fe642f..c5a0fd8 100644
--- a/pkg/test_runner/lib/src/test_file.dart
+++ b/pkg/test_runner/lib/src/test_file.dart
@@ -64,14 +64,24 @@
/// generated from a multitest. Otherwise, returns an empty string.
String get multitestKey;
- /// If the text contains static error expectations, it's a "static error
+ /// If the test contains static error expectations, it's a "static error
/// test".
///
/// These tests exist to validate that a front end reports the right static
- /// errors. They are skipped on configurations that don't intend to test
- /// static error reporting.
+ /// errors. Unless the expected errors are all warnings, a static error test
+ /// is skipped on configurations that are not purely front end.
bool get isStaticErrorTest => expectedErrors.isNotEmpty;
+ /// If the tests has no static error expectations, or all of the expectations
+ /// are warnings, then the test tests runtime semantics.
+ ///
+ /// Note that this is *not* the negation of [isStaticErrorTest]. A test that
+ /// contains only warning expectations is both a static "error" test and a
+ /// runtime test. The test runner will validate that the front ends produce
+ /// the expected warnings *and* that a runtime also correctly executes the
+ /// test.
+ bool get isRuntimeTest => expectedErrors.every((error) => error.isWarning);
+
/// A hash code used to spread tests across shards.
int get shardHash {
// The VM C++ unit tests have a special fake TestFile with no suite
diff --git a/pkg/test_runner/lib/src/test_suite.dart b/pkg/test_runner/lib/src/test_suite.dart
index 4351b8d..d05d3c1 100644
--- a/pkg/test_runner/lib/src/test_suite.dart
+++ b/pkg/test_runner/lib/src/test_suite.dart
@@ -557,16 +557,14 @@
/// options.
void _testCasesFromTestFile(
TestFile testFile, ExpectationSet expectations, TestCaseEvent onTest) {
- // Static error tests are skipped on every implementation except analyzer
- // and Fasta.
- // TODO(rnystrom): Should other configurations that use CFE support static
- // error tests?
// TODO(rnystrom): Skipping this here is a little unusual because most
// skips are handled in _addTestCase(). However, if the configuration
// is running on a browser, calling _addTestCase() will try to create
// a set of commands which ultimately causes an exception in
// DummyRuntimeConfiguration. This avoids that.
- if (testFile.isStaticErrorTest &&
+ // If the test only has static expectations, skip it on any configurations
+ // that are not purely front ends.
+ if (!testFile.isRuntimeTest &&
configuration.compiler != Compiler.dart2analyzer &&
configuration.compiler != Compiler.fasta) {
return;
@@ -579,7 +577,7 @@
var expectationSet = expectations.expectations(testFile.name);
if (configuration.compilerConfiguration.hasCompiler &&
- (testFile.hasCompileError || testFile.isStaticErrorTest)) {
+ (testFile.hasCompileError || !testFile.isRuntimeTest)) {
// If a compile-time error is expected, and we're testing a
// compiler, we never need to attempt to run the program (in a
// browser or otherwise).
diff --git a/pkg/test_runner/test/static_error_test.dart b/pkg/test_runner/test/static_error_test.dart
index 711e69b..a3e9897 100644
--- a/pkg/test_runner/test/static_error_test.dart
+++ b/pkg/test_runner/test/static_error_test.dart
@@ -11,6 +11,7 @@
void main() {
testHasError();
testErrorFor();
+ testIsWarning();
testIsSpecifiedFor();
testCompareTo();
testDescribeDifferences();
@@ -78,6 +79,42 @@
Expect.equals("Web.", all.errorFor(ErrorSource.web));
}
+void testIsWarning() {
+ // Analyzer only.
+ Expect.isTrue(
+ makeError(analyzerError: "STATIC_WARNING.INVALID_OPTION").isWarning);
+ Expect.isFalse(
+ makeError(analyzerError: "SYNTACTIC_ERROR.MISSING_FUNCTION_BODY")
+ .isWarning);
+ Expect.isFalse(makeError(
+ analyzerError: "COMPILE_TIME_ERROR.NOT_ENOUGH_POSITIONAL_ARGUMENTS")
+ .isWarning);
+
+ // CFE only.
+ Expect.isFalse(makeError(cfeError: "Any error message.").isWarning);
+
+ // Web only.
+ Expect.isFalse(makeError(webError: "Any error message.").isWarning);
+
+ // Multiple front ends.
+ Expect.isFalse(makeError(
+ analyzerError: "STATIC_WARNING.INVALID_OPTION",
+ cfeError: "Any error message.")
+ .isWarning);
+ Expect.isFalse(
+ makeError(cfeError: "Any error message.", webError: "Any error message.")
+ .isWarning);
+ Expect.isFalse(makeError(
+ analyzerError: "STATIC_WARNING.INVALID_OPTION",
+ webError: "Any error message.")
+ .isWarning);
+ Expect.isFalse(makeError(
+ analyzerError: "STATIC_WARNING.INVALID_OPTION",
+ cfeError: "Any error message.",
+ webError: "Any error message.")
+ .isWarning);
+}
+
void testIsSpecifiedFor() {
var specifiedAll = makeError(
line: 1,
diff --git a/pkg/test_runner/test/test_file_test.dart b/pkg/test_runner/test/test_file_test.dart
index 847fb49..251f60d 100644
--- a/pkg/test_runner/test/test_file_test.dart
+++ b/pkg/test_runner/test/test_file_test.dart
@@ -28,6 +28,7 @@
testParseMultitest();
testParseErrorFlags();
testParseErrorExpectations();
+ testIsRuntimeTest();
testName();
testMultitest();
testShardHash();
@@ -590,6 +591,53 @@
""");
}
+void testIsRuntimeTest() {
+ // No static errors at all.
+ var file = parseTestFile("");
+ Expect.isTrue(file.isRuntimeTest);
+
+ // Only warnings.
+ file = parseTestFile("""
+ int i = "s";
+ /\/ ^^^
+ /\/ [analyzer] STATIC_WARNING.INVALID_OPTION
+ /\/ ^^^
+ /\/ [analyzer] STATIC_WARNING.INVALID_OPTION
+ """);
+ Expect.isTrue(file.isRuntimeTest);
+
+ // Errors.
+ file = parseTestFile("""
+ int i = "s";
+ /\/ ^^^
+ /\/ [analyzer] COMPILE_TIME_ERROR.NOT_ENOUGH_POSITIONAL_ARGUMENTS
+ """);
+ Expect.isFalse(file.isRuntimeTest);
+
+ file = parseTestFile("""
+ int i = "s";
+ /\/ ^^^
+ /\/ [cfe] Error message.
+ """);
+ Expect.isFalse(file.isRuntimeTest);
+
+ file = parseTestFile("""
+ int i = "s";
+ /\/ ^^^
+ /\/ [web] Error message.
+ """);
+ Expect.isFalse(file.isRuntimeTest);
+
+ // Mixed errors and warnings.
+ file = parseTestFile("""
+ int i = "s";
+ /\/ ^^^
+ /\/ [analyzer] STATIC_WARNING.INVALID_OPTION
+ /\/ [cfe] Error message.
+ """);
+ Expect.isFalse(file.isRuntimeTest);
+}
+
void testName() {
// Immediately inside suite.
var file = TestFile.parse(Path("suite").absolute,
diff --git a/pkg/test_runner/test/utils.dart b/pkg/test_runner/test/utils.dart
index e8a87be..8c1e83a 100644
--- a/pkg/test_runner/test/utils.dart
+++ b/pkg/test_runner/test/utils.dart
@@ -26,8 +26,8 @@
_MockTestSuite(configuration, testFiles);
StaticError makeError(
- {int line,
- int column,
+ {int line = 1,
+ int column = 2,
int length,
String analyzerError,
String cfeError,
diff --git a/pkg/vm/lib/bytecode/gen_bytecode.dart b/pkg/vm/lib/bytecode/gen_bytecode.dart
index ae66a6a6..88cff2c 100644
--- a/pkg/vm/lib/bytecode/gen_bytecode.dart
+++ b/pkg/vm/lib/bytecode/gen_bytecode.dart
@@ -4387,7 +4387,12 @@
tryBlock.types.add(cp.addType(catchClause.guard));
Label skipCatch;
- if (catchClause.guard == const DynamicType()) {
+ final guardType = catchClause.guard;
+ // Exception objects are guaranteed to be non-nullable, so
+ // non-nullable Object is also a catch-all type.
+ if (guardType is DynamicType ||
+ (guardType is InterfaceType &&
+ guardType.classNode == coreTypes.objectClass)) {
hasCatchAll = true;
} else {
asm.emitPush(exception);
diff --git a/pkg/vm/lib/transformations/type_flow/summary_collector.dart b/pkg/vm/lib/transformations/type_flow/summary_collector.dart
index 43c9e3e..d76503d 100644
--- a/pkg/vm/lib/transformations/type_flow/summary_collector.dart
+++ b/pkg/vm/lib/transformations/type_flow/summary_collector.dart
@@ -762,6 +762,13 @@
}
}
+ if (member.name.name == '==') {
+ // In addition to what is returned from the function body,
+ // operator == performs implicit comparison with null
+ // and returns bool.
+ _returnValue.values.add(_boolType);
+ }
+
_summary.result = _returnValue;
}
diff --git a/pkg/vm/tool/gen_kernel b/pkg/vm/tool/gen_kernel
index 8174ed5..d0494c7 100755
--- a/pkg/vm/tool/gen_kernel
+++ b/pkg/vm/tool/gen_kernel
@@ -8,25 +8,6 @@
set -e
-ABI_VERSION=""
-HAS_PLATFORM=""
-ARGV=()
-
-for arg in "$@"; do
- case $arg in
- --use-abi-version=*)
- ABI_VERSION="$(echo "$arg" | sed "s|--use-abi-version=||")"
- ;;
- --platform*)
- HAS_PLATFORM="TRUE"
- ARGV+=("$arg")
- ;;
- *)
- ARGV+=("$arg")
- ;;
- esac
-done
-
function follow_links() {
file="$1"
while [ -h "$file" ]; do
@@ -54,18 +35,4 @@
OUT_DIR="$SDK_DIR/out"
fi
-export DART_CONFIGURATION=${DART_CONFIGURATION:-ReleaseX64}
-BIN_DIR="$OUT_DIR/$DART_CONFIGURATION"
-
-if [ $ABI_VERSION ]; then
- ABI_DIR="$BIN_DIR/dart-sdk/lib/_internal/abiversions/$ABI_VERSION"
- PLATFORM=()
- if [ -z $HAS_PLATFORM ]; then
- PLATFORM+=("--platform" "$ABI_DIR/vm_platform_strong.dill")
- fi
- exec "$BIN_DIR/dart" $DART_VM_FLAGS --enable-interpreter \
- "$ABI_DIR/gen_kernel_bytecode.dill" "${PLATFORM[@]}" "${ARGV[@]}"
-else
- exec "$DART" $DART_VM_FLAGS \
- "${SDK_DIR}/pkg/vm/bin/gen_kernel.dart" "${ARGV[@]}"
-fi
+exec "$DART" $DART_VM_FLAGS "${SDK_DIR}/pkg/vm/bin/gen_kernel.dart" $@
diff --git a/pkg/vm_snapshot_analysis/CHANGELOG.md b/pkg/vm_snapshot_analysis/CHANGELOG.md
index 2bfcd15..36d229f 100644
--- a/pkg/vm_snapshot_analysis/CHANGELOG.md
+++ b/pkg/vm_snapshot_analysis/CHANGELOG.md
@@ -1,5 +1,9 @@
# Changelog
+## 0.5.3
+- Add `compareProgramInfo` that takes in two program info objects and outputs
+a `Map` object containing the diff data.
+
## 0.5.2
- Add support for package paths that look like `package:foo.bar.baz/src/foobar.dart`
- Move `commands` back to lib.
diff --git a/pkg/vm_snapshot_analysis/lib/treemap.dart b/pkg/vm_snapshot_analysis/lib/treemap.dart
index 68103f3..36ce891 100644
--- a/pkg/vm_snapshot_analysis/lib/treemap.dart
+++ b/pkg/vm_snapshot_analysis/lib/treemap.dart
@@ -196,7 +196,7 @@
/// given [v8_profile.Node].
final Map<TreemapFormat, String Function(v8_profile.Node)> _nameFormatters = {
TreemapFormat.dataAndCode: (n) => _isExecutableCode(n) ? '<code>' : '<data>',
- TreemapFormat.objectType: (n) => n.type,
+ TreemapFormat.objectType: (n) => '<${n.type}>',
};
/// Returns a /-separated path to the given symbol within the treemap.
diff --git a/pkg/vm_snapshot_analysis/lib/utils.dart b/pkg/vm_snapshot_analysis/lib/utils.dart
index c226dad..abf3eb3 100644
--- a/pkg/vm_snapshot_analysis/lib/utils.dart
+++ b/pkg/vm_snapshot_analysis/lib/utils.dart
@@ -30,8 +30,13 @@
final newSizes = loadProgramInfoFromJson(newJson,
collapseAnonymousClosures: collapseAnonymousClosures);
- final diff = computeDiff(oldSizes, newSizes);
+ return compareProgramInfo(oldSizes, newSizes, format: format);
+}
+Map<String, dynamic> compareProgramInfo(
+ ProgramInfo oldSizes, ProgramInfo newSizes,
+ {TreemapFormat format = TreemapFormat.collapsed}) {
+ final diff = computeDiff(oldSizes, newSizes);
return treemapFromInfo(diff, format: format);
}
diff --git a/pkg/vm_snapshot_analysis/pubspec.yaml b/pkg/vm_snapshot_analysis/pubspec.yaml
index 66e7a37..fce4b3d 100644
--- a/pkg/vm_snapshot_analysis/pubspec.yaml
+++ b/pkg/vm_snapshot_analysis/pubspec.yaml
@@ -1,6 +1,6 @@
name: vm_snapshot_analysis
description: Utilities for analysing AOT snapshot size.
-version: 0.5.2
+version: 0.5.3
homepage: https://github.com/dart-lang/sdk/tree/master/pkg/vm_snapshot_analysis
diff --git a/runtime/bin/BUILD.gn b/runtime/bin/BUILD.gn
index fb682c0..1b44cd3 100644
--- a/runtime/bin/BUILD.gn
+++ b/runtime/bin/BUILD.gn
@@ -160,7 +160,7 @@
"..:dart_config",
"..:dart_precompiler_config",
] + extra_configs
- deps = [ ":generate_abi_version_cc_file" ] + extra_deps
+ deps = extra_deps
defines = [ "EXCLUDE_CFE_AND_KERNEL_PLATFORM" ]
@@ -178,7 +178,6 @@
"snapshot_utils.h",
# Very limited native resolver provided.
- "$target_gen_dir/abi_version.cc",
"builtin_gen_snapshot.cc",
"dfe.cc",
"dfe.h",
@@ -728,25 +727,6 @@
get_target_outputs(":platform_strong_dill_linkable")
}
-action("generate_abi_version_cc_file") {
- inputs = [
- "../../tools/utils.py",
- "../../tools/VERSION",
- "abi_version_in.cc",
- ]
- output = "$target_gen_dir/abi_version.cc"
- outputs = [ output ]
-
- script = "../../tools/make_version.py"
- args = [
- "--quiet",
- "--output",
- rebase_path(output, root_build_dir),
- "--input",
- rebase_path("abi_version_in.cc", root_build_dir),
- ]
-}
-
template("dart_executable") {
use_product_mode = dart_runtime_mode == "release"
if (defined(invoker.use_product_mode)) {
@@ -803,7 +783,6 @@
deps = [
":crashpad",
- ":generate_abi_version_cc_file",
"//third_party/boringssl",
"//third_party/zlib",
]
@@ -840,7 +819,6 @@
"snapshot_utils.h",
"vmservice_impl.cc",
"vmservice_impl.h",
- "$target_gen_dir/abi_version.cc",
] + extra_sources
if (is_win) {
@@ -1006,7 +984,6 @@
":dart_kernel_platform_cc",
":dart_snapshot_cc",
":gen_kernel_bytecode_dill",
- ":generate_abi_version_cc_file",
":standalone_dart_io",
"..:libdart_precompiler",
"//third_party/zlib",
@@ -1043,7 +1020,6 @@
heap_tests = rebase_path(heap_sources_tests, ".", "../vm/heap")
sources = [
- "$target_gen_dir/abi_version.cc",
"builtin.cc",
"dfe.cc",
"dfe.h",
diff --git a/runtime/bin/abi_version.h b/runtime/bin/abi_version.h
deleted file mode 100644
index acd0cdf..0000000
--- a/runtime/bin/abi_version.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) 2019, 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.
-
-#ifndef RUNTIME_BIN_ABI_VERSION_H_
-#define RUNTIME_BIN_ABI_VERSION_H_
-
-namespace dart {
-
-class AbiVersion {
- public:
- static int GetCurrent();
- static int GetOldestSupported();
-};
-
-} // namespace dart
-
-#endif // RUNTIME_BIN_ABI_VERSION_H_
diff --git a/runtime/bin/abi_version_in.cc b/runtime/bin/abi_version_in.cc
deleted file mode 100644
index ad737b2..0000000
--- a/runtime/bin/abi_version_in.cc
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2019, 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.
-
-#include "bin/abi_version.h"
-
-namespace dart {
-
-int AbiVersion::GetCurrent() {
- return {{ABI_VERSION}};
-}
-
-int AbiVersion::GetOldestSupported() {
- return {{OLDEST_SUPPORTED_ABI_VERSION}};
-}
-
-} // namespace dart
diff --git a/runtime/bin/builtin_impl_sources.gni b/runtime/bin/builtin_impl_sources.gni
index 90790d3..b8ea4eb 100644
--- a/runtime/bin/builtin_impl_sources.gni
+++ b/runtime/bin/builtin_impl_sources.gni
@@ -7,7 +7,6 @@
# io_impl_sources.gypi.
builtin_impl_sources = [
- "abi_version.h",
"crypto.cc",
"crypto.h",
"crypto_android.cc",
diff --git a/runtime/bin/dfe.cc b/runtime/bin/dfe.cc
index 58718b7..755ef82 100644
--- a/runtime/bin/dfe.cc
+++ b/runtime/bin/dfe.cc
@@ -4,13 +4,11 @@
#include "bin/dfe.h"
-#include "bin/abi_version.h"
#include "bin/dartutils.h"
#include "bin/directory.h"
#include "bin/error_exit.h"
#include "bin/exe_utils.h"
#include "bin/file.h"
-#include "bin/main_options.h"
#include "bin/platform.h"
#include "bin/utils.h"
#include "include/dart_tools_api.h"
@@ -33,6 +31,28 @@
namespace dart {
namespace bin {
+// The run_vm_tests binary has the DART_PRECOMPILER set in order to allow unit
+// tests to exercise JIT and AOT pipeline.
+//
+// Only on X64 do we have kernel-service.dart.snapshot available otherwise we
+// need to fall back to the built-in one (if we have it).
+#if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) || \
+ (defined(DART_PRECOMPILER) && defined(TARGET_ARCH_X64))
+const uint8_t* kernel_service_dill = nullptr;
+const intptr_t kernel_service_dill_size = 0;
+#else
+const uint8_t* kernel_service_dill = kKernelServiceDill;
+const intptr_t kernel_service_dill_size = kKernelServiceDillSize;
+#endif
+
+#if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
+const uint8_t* platform_strong_dill = nullptr;
+const intptr_t platform_strong_dill_size = 0;
+#else
+const uint8_t* platform_strong_dill = kPlatformStrongDill;
+const intptr_t platform_strong_dill_size = kPlatformStrongDillSize;
+#endif
+
#if !defined(DART_PRECOMPILED_RUNTIME)
DFE dfe;
#endif
@@ -46,31 +66,6 @@
frontend_filename_(nullptr),
application_kernel_buffer_(nullptr),
application_kernel_buffer_size_(0) {
- // The run_vm_tests binary has the DART_PRECOMPILER set in order to allow unit
- // tests to exercise JIT and AOT pipeline.
- //
- // Only on X64 do we have kernel-service.dart.snapshot available otherwise we
- // need to fall back to the built-in one (if we have it).
-#if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM) || \
- (defined(DART_PRECOMPILER) && defined(TARGET_ARCH_X64))
- kernel_service_dill_ = nullptr;
- kernel_service_dill_size_ = 0;
-#else
- kernel_service_dill_ = kKernelServiceDill;
- kernel_service_dill_size_ = kKernelServiceDillSize;
-#endif
-
-#if defined(EXCLUDE_CFE_AND_KERNEL_PLATFORM)
- platform_strong_dill_for_compilation_ = nullptr;
- platform_strong_dill_for_compilation_size_ = 0;
- platform_strong_dill_for_execution_ = nullptr;
- platform_strong_dill_for_execution_size_ = 0;
-#else
- platform_strong_dill_for_compilation_ = kPlatformStrongDill;
- platform_strong_dill_for_compilation_size_ = kPlatformStrongDillSize;
- platform_strong_dill_for_execution_ = kPlatformStrongDill;
- platform_strong_dill_for_execution_size_ = kPlatformStrongDillSize;
-#endif
}
DFE::~DFE() {
@@ -85,72 +80,28 @@
}
void DFE::Init() {
- Init(Options::kAbiVersionUnset);
-}
-
-void DFE::Init(int target_abi_version) {
- if (platform_strong_dill_for_compilation_ == nullptr) {
+ if (platform_strong_dill == nullptr) {
return;
}
- if (!InitKernelServiceAndPlatformDills(target_abi_version)) {
- return;
- }
-
- Dart_SetDartLibrarySourcesKernel(platform_strong_dill_for_compilation_,
- platform_strong_dill_for_compilation_size_);
+ InitKernelServiceAndPlatformDills();
+ Dart_SetDartLibrarySourcesKernel(platform_strong_dill,
+ platform_strong_dill_size);
}
-bool DFE::InitKernelServiceAndPlatformDills(int target_abi_version) {
- const char kAbiVersionsDir[] = "dart-sdk/lib/_internal/abiversions";
- const char kKernelServiceDillFile[] = "kernel_service.dill";
- const char kPlatformStrongDillFile[] = "vm_platform_strong.dill";
-
+void DFE::InitKernelServiceAndPlatformDills() {
if (frontend_filename_ != nullptr) {
- return true;
+ return;
}
// |dir_prefix| includes the last path seperator.
auto dir_prefix = EXEUtils::GetDirectoryPrefixFromExeName();
- if (target_abi_version != Options::kAbiVersionUnset) {
- kernel_service_dill_ = nullptr;
- kernel_service_dill_size_ = 0;
- platform_strong_dill_for_compilation_ = nullptr;
- platform_strong_dill_for_compilation_size_ = 0;
-
- // Look in the old abi version directory.
- char* script_uri =
- Utils::SCreate("%s%s/%d/%s", dir_prefix.get(), kAbiVersionsDir,
- target_abi_version, kPlatformStrongDillFile);
- if (!TryReadKernelFile(
- script_uri,
- const_cast<uint8_t**>(&platform_strong_dill_for_compilation_),
- &platform_strong_dill_for_compilation_size_)) {
- Syslog::PrintErr("Can't find old ABI dill file: %s\n", script_uri);
- free(script_uri);
- return false;
- }
- free(script_uri);
- script_uri = Utils::SCreate("%s%s/%d/%s", dir_prefix.get(), kAbiVersionsDir,
- target_abi_version, kKernelServiceDillFile);
- if (!TryReadKernelFile(script_uri,
- const_cast<uint8_t**>(&kernel_service_dill_),
- &kernel_service_dill_size_)) {
- Syslog::PrintErr("Can't find old ABI dill file: %s\n", script_uri);
- free(script_uri);
- return false;
- } else {
- frontend_filename_ = script_uri;
- return true;
- }
- }
-
// Look for the frontend snapshot next to the executable.
frontend_filename_ =
Utils::SCreate("%s%s", dir_prefix.get(), kKernelServiceSnapshot);
if (File::Exists(nullptr, frontend_filename_)) {
- return true;
+ return;
}
free(frontend_filename_);
frontend_filename_ = nullptr;
@@ -161,31 +112,30 @@
Utils::SCreate("%s%s%s%s", dir_prefix.get(), kSnapshotsDirectory,
File::PathSeparator(), kKernelServiceSnapshot);
if (File::Exists(nullptr, frontend_filename_)) {
- return true;
+ return;
}
free(frontend_filename_);
frontend_filename_ = nullptr;
- return true;
}
bool DFE::KernelServiceDillAvailable() const {
- return kernel_service_dill_ != nullptr;
+ return kernel_service_dill != nullptr;
}
void DFE::LoadKernelService(const uint8_t** kernel_service_buffer,
intptr_t* kernel_service_buffer_size) {
- *kernel_service_buffer = kernel_service_dill_;
- *kernel_service_buffer_size = kernel_service_dill_size_;
+ *kernel_service_buffer = kernel_service_dill;
+ *kernel_service_buffer_size = kernel_service_dill_size;
}
void DFE::LoadPlatform(const uint8_t** kernel_buffer,
intptr_t* kernel_buffer_size) {
- *kernel_buffer = platform_strong_dill_for_execution_;
- *kernel_buffer_size = platform_strong_dill_for_execution_size_;
+ *kernel_buffer = platform_strong_dill;
+ *kernel_buffer_size = platform_strong_dill_size;
}
bool DFE::CanUseDartFrontend() const {
- return (platform_strong_dill_for_compilation_ != nullptr) &&
+ return (platform_strong_dill != nullptr) &&
(KernelServiceDillAvailable() || (frontend_filename() != nullptr));
}
@@ -238,9 +188,9 @@
PathSanitizer path_sanitizer(script_uri);
const char* sanitized_uri = path_sanitizer.sanitized_uri();
- return Dart_CompileToKernel(
- sanitized_uri, platform_strong_dill_for_compilation_,
- platform_strong_dill_for_compilation_size_, incremental, package_config);
+ return Dart_CompileToKernel(sanitized_uri, platform_strong_dill,
+ platform_strong_dill_size, incremental,
+ package_config);
}
void DFE::CompileAndReadScript(const char* script_uri,
diff --git a/runtime/bin/dfe.h b/runtime/bin/dfe.h
index c75b6ea..eb475bf 100644
--- a/runtime/bin/dfe.h
+++ b/runtime/bin/dfe.h
@@ -24,7 +24,6 @@
// Call Init before Dart_Initialize to prevent races between the
// different isolates.
void Init();
- void Init(int target_abi_version);
char* frontend_filename() const { return frontend_filename_; }
@@ -108,18 +107,12 @@
bool use_dfe_;
bool use_incremental_compiler_;
char* frontend_filename_;
- const uint8_t* kernel_service_dill_;
- intptr_t kernel_service_dill_size_;
- const uint8_t* platform_strong_dill_for_compilation_;
- intptr_t platform_strong_dill_for_compilation_size_;
- const uint8_t* platform_strong_dill_for_execution_;
- intptr_t platform_strong_dill_for_execution_size_;
// Kernel binary specified on the cmd line.
uint8_t* application_kernel_buffer_;
intptr_t application_kernel_buffer_size_;
- bool InitKernelServiceAndPlatformDills(int target_abi_version);
+ void InitKernelServiceAndPlatformDills();
DISALLOW_COPY_AND_ASSIGN(DFE);
};
diff --git a/runtime/bin/eventhandler_fuchsia.cc b/runtime/bin/eventhandler_fuchsia.cc
index 8394deb..f15bc3b 100644
--- a/runtime/bin/eventhandler_fuchsia.cc
+++ b/runtime/bin/eventhandler_fuchsia.cc
@@ -399,7 +399,7 @@
} else if ((old_mask == 0) && (new_mask != 0)) {
AddToPort(port_handle_, di);
} else if ((old_mask != 0) && (new_mask != 0)) {
- ASSERT(!di->IsListeningSocket());
+ ASSERT((old_mask == new_mask) || !di->IsListeningSocket());
RemoveFromPort(port_handle_, di);
AddToPort(port_handle_, di);
}
diff --git a/runtime/bin/file_fuchsia.cc b/runtime/bin/file_fuchsia.cc
index d1918b0..e2e87d8 100644
--- a/runtime/bin/file_fuchsia.cc
+++ b/runtime/bin/file_fuchsia.cc
@@ -9,6 +9,7 @@
#include <errno.h> // NOLINT
#include <fcntl.h> // NOLINT
+#include <lib/fdio/fdio.h> // NOLINT
#include <lib/fdio/namespace.h> // NOLINT
#include <libgen.h> // NOLINT
#include <sys/mman.h> // NOLINT
@@ -51,8 +52,10 @@
void File::Close() {
ASSERT(handle_->fd() >= 0);
if (handle_->fd() == STDOUT_FILENO) {
- // If stdout, redirect fd to /dev/null.
- int null_fd = NO_RETRY_EXPECTED(open("/dev/null", O_WRONLY));
+ // If stdout, redirect fd to Fuchsia's equivalent of /dev/null.
+ auto* null_fdio = fdio_null_create();
+ ASSERT(null_fdio != nullptr);
+ int null_fd = NO_RETRY_EXPECTED(fdio_bind_to_fd(null_fdio, -1, 0));
ASSERT(null_fd >= 0);
VOID_NO_RETRY_EXPECTED(dup2(null_fd, handle_->fd()));
VOID_NO_RETRY_EXPECTED(close(null_fd));
diff --git a/runtime/bin/gen_snapshot.cc b/runtime/bin/gen_snapshot.cc
index 2cf7ab9..f2d33c5 100644
--- a/runtime/bin/gen_snapshot.cc
+++ b/runtime/bin/gen_snapshot.cc
@@ -608,7 +608,7 @@
line.Printf("{ \"id\": %" Pd ", \"path\": \"", id);
line.AddEscapedString(path);
line.Printf("\" }");
- if (!manifest_file->Print("%s\n", line.buf())) {
+ if (!manifest_file->Print("%s\n", line.buffer())) {
PrintErrAndExit("Error: Unable to write file: %s\n\n",
loading_unit_manifest_filename);
}
diff --git a/runtime/bin/main.cc b/runtime/bin/main.cc
index 5f9c5e5..69d82b0 100644
--- a/runtime/bin/main.cc
+++ b/runtime/bin/main.cc
@@ -1163,7 +1163,7 @@
// they might affect how the platform is loaded.
#if !defined(DART_PRECOMPILED_RUNTIME)
if (script_name != nullptr) {
- dfe.Init(Options::target_abi_version());
+ dfe.Init();
uint8_t* application_kernel_buffer = NULL;
intptr_t application_kernel_buffer_size = 0;
dfe.ReadScript(script_name, &application_kernel_buffer,
diff --git a/runtime/bin/main_options.cc b/runtime/bin/main_options.cc
index 42a677b6..8fa4f79 100644
--- a/runtime/bin/main_options.cc
+++ b/runtime/bin/main_options.cc
@@ -8,7 +8,6 @@
#include <stdlib.h>
#include <string.h>
-#include "bin/abi_version.h"
#include "bin/dartdev_isolate.h"
#include "bin/error_exit.h"
#include "bin/options.h"
@@ -373,33 +372,6 @@
return false;
}
-int Options::target_abi_version_ = Options::kAbiVersionUnset;
-bool Options::ProcessAbiVersionOption(const char* arg,
- CommandLineOptions* vm_options) {
- const char* value = OptionProcessor::ProcessOption(arg, "--use_abi_version=");
- if (value == NULL) {
- return false;
- }
- int ver = 0;
- for (int i = 0; value[i] != '\0'; ++i) {
- if (value[i] >= '0' && value[i] <= '9') {
- ver = (ver * 10) + value[i] - '0';
- } else {
- Syslog::PrintErr("--use_abi_version must be an int\n");
- return false;
- }
- }
- if (ver < AbiVersion::GetOldestSupported() ||
- ver > AbiVersion::GetCurrent()) {
- Syslog::PrintErr("--use_abi_version must be between %d and %d inclusive\n",
- AbiVersion::GetOldestSupported(),
- AbiVersion::GetCurrent());
- return false;
- }
- target_abi_version_ = ver;
- return true;
-}
-
bool Options::ProcessEnableExperimentOption(const char* arg,
CommandLineOptions* vm_options) {
const char* value =
diff --git a/runtime/bin/main_options.h b/runtime/bin/main_options.h
index 90234e0..76c50be 100644
--- a/runtime/bin/main_options.h
+++ b/runtime/bin/main_options.h
@@ -69,7 +69,6 @@
V(ProcessEnvironmentOption) \
V(ProcessEnableVmServiceOption) \
V(ProcessObserveOption) \
- V(ProcessAbiVersionOption) \
V(ProcessEnableExperimentOption) \
V(ProcessVMDebuggingOptions)
@@ -127,9 +126,6 @@
static const char* vm_service_server_ip() { return vm_service_server_ip_; }
static int vm_service_server_port() { return vm_service_server_port_; }
- static constexpr int kAbiVersionUnset = -1;
- static int target_abi_version() { return target_abi_version_; }
-
#if !defined(DART_PRECOMPILED_RUNTIME)
static DFE* dfe() { return dfe_; }
static void set_dfe(DFE* dfe) { dfe_ = dfe; }
@@ -178,7 +174,6 @@
int default_port,
const char* default_ip);
- static int target_abi_version_;
static MallocGrowableArray<const char*> enabled_experiments_;
#define OPTION_FRIEND(flag, variable) friend class OptionProcessor_##flag;
diff --git a/runtime/bin/namespace_android.cc b/runtime/bin/namespace_android.cc
index 62a69f8..f5a2a9f 100644
--- a/runtime/bin/namespace_android.cc
+++ b/runtime/bin/namespace_android.cc
@@ -61,7 +61,7 @@
// Normalize it.
char result[PATH_MAX];
const intptr_t result_len =
- File::CleanUnixPath(tbuf.buf(), result, PATH_MAX);
+ File::CleanUnixPath(tbuf.buffer(), result, PATH_MAX);
if (result_len < 0) {
errno = ENAMETOOLONG;
return false;
diff --git a/runtime/bin/namespace_fuchsia.cc b/runtime/bin/namespace_fuchsia.cc
index 6e93bcb..c8cfbcb 100644
--- a/runtime/bin/namespace_fuchsia.cc
+++ b/runtime/bin/namespace_fuchsia.cc
@@ -81,7 +81,7 @@
// Normalize it.
char result[PATH_MAX];
const intptr_t result_len =
- File::CleanUnixPath(tbuf.buf(), result, PATH_MAX);
+ File::CleanUnixPath(tbuf.buffer(), result, PATH_MAX);
if (result_len < 0) {
errno = ENAMETOOLONG;
return false;
diff --git a/runtime/bin/namespace_linux.cc b/runtime/bin/namespace_linux.cc
index 6cb3e07..416ea3d 100644
--- a/runtime/bin/namespace_linux.cc
+++ b/runtime/bin/namespace_linux.cc
@@ -61,7 +61,7 @@
// Normalize it.
char result[PATH_MAX];
const intptr_t result_len =
- File::CleanUnixPath(tbuf.buf(), result, PATH_MAX);
+ File::CleanUnixPath(tbuf.buffer(), result, PATH_MAX);
if (result_len < 0) {
errno = ENAMETOOLONG;
return false;
diff --git a/runtime/bin/secure_socket_filter.cc b/runtime/bin/secure_socket_filter.cc
index a21bc8e..207971f 100644
--- a/runtime/bin/secure_socket_filter.cc
+++ b/runtime/bin/secure_socket_filter.cc
@@ -245,7 +245,8 @@
SecureSocketUtils::FetchErrorString(filter->ssl_, &error_string);
CObjectArray* result = new CObjectArray(CObject::NewArray(2));
result->SetAt(0, new CObjectInt32(CObject::NewInt32(error_code)));
- result->SetAt(1, new CObjectString(CObject::NewString(error_string.buf())));
+ result->SetAt(1,
+ new CObjectString(CObject::NewString(error_string.buffer())));
return result;
}
}
diff --git a/runtime/bin/secure_socket_utils.cc b/runtime/bin/secure_socket_utils.cc
index 259b06e..e3cdbf4 100644
--- a/runtime/bin/secure_socket_utils.cc
+++ b/runtime/bin/secure_socket_utils.cc
@@ -54,7 +54,7 @@
{
TextBuffer error_string(SSL_ERROR_MESSAGE_BUFFER_SIZE);
SecureSocketUtils::FetchErrorString(ssl, &error_string);
- OSError os_error_struct(status, error_string.buf(), OSError::kBoringSSL);
+ OSError os_error_struct(status, error_string.buffer(), OSError::kBoringSSL);
Dart_Handle os_error = DartUtils::NewDartOSError(&os_error_struct);
exception =
DartUtils::NewDartIOException(exception_type, message, os_error);
diff --git a/runtime/platform/text_buffer.cc b/runtime/platform/text_buffer.cc
index ed2c640..5d08892 100644
--- a/runtime/platform/text_buffer.cc
+++ b/runtime/platform/text_buffer.cc
@@ -11,73 +11,52 @@
namespace dart {
-TextBuffer::TextBuffer(intptr_t buf_size) {
- ASSERT(buf_size > 0);
- buf_ = reinterpret_cast<char*>(malloc(buf_size));
- if (buf_ == NULL) {
- OUT_OF_MEMORY();
- }
- buf_size_ = buf_size;
- Clear();
-}
-
-TextBuffer::~TextBuffer() {
- free(buf_);
- buf_ = NULL;
-}
-
-void TextBuffer::Clear() {
- msg_len_ = 0;
- buf_[0] = '\0';
-}
-
-char* TextBuffer::Steal() {
- char* r = buf_;
- buf_ = NULL;
- buf_size_ = 0;
- msg_len_ = 0;
- return r;
-}
-
-void TextBuffer::AddChar(char ch) {
- EnsureCapacity(sizeof(ch));
- buf_[msg_len_] = ch;
- msg_len_++;
- buf_[msg_len_] = '\0';
-}
-
-void TextBuffer::AddRaw(const uint8_t* buffer, intptr_t buffer_length) {
- EnsureCapacity(buffer_length);
- memmove(&buf_[msg_len_], buffer, buffer_length);
- msg_len_ += buffer_length;
- buf_[msg_len_] = '\0';
-}
-
-intptr_t TextBuffer::Printf(const char* format, ...) {
+intptr_t BaseTextBuffer::Printf(const char* format, ...) {
va_list args;
va_start(args, format);
- intptr_t remaining = buf_size_ - msg_len_;
+ intptr_t remaining = capacity_ - length_;
ASSERT(remaining >= 0);
- intptr_t len = Utils::VSNPrint(buf_ + msg_len_, remaining, format, args);
+ intptr_t len = Utils::VSNPrint(buffer_ + length_, remaining, format, args);
va_end(args);
if (len >= remaining) {
- EnsureCapacity(len);
- remaining = buf_size_ - msg_len_;
+ if (!EnsureCapacity(len)) {
+ length_ = capacity_ - 1;
+ buffer_[length_] = '\0';
+ return remaining - 1;
+ }
+ remaining = capacity_ - length_;
ASSERT(remaining > len);
va_list args2;
va_start(args2, format);
- intptr_t len2 = Utils::VSNPrint(buf_ + msg_len_, remaining, format, args2);
+ intptr_t len2 =
+ Utils::VSNPrint(buffer_ + length_, remaining, format, args2);
va_end(args2);
ASSERT(len == len2);
}
- msg_len_ += len;
- buf_[msg_len_] = '\0';
+ length_ += len;
+ buffer_[length_] = '\0';
return len;
}
+void BaseTextBuffer::AddChar(char ch) {
+ if (!EnsureCapacity(sizeof(ch))) return;
+ buffer_[length_] = ch;
+ length_++;
+ buffer_[length_] = '\0';
+}
+
+void BaseTextBuffer::AddRaw(const uint8_t* buffer, intptr_t buffer_length) {
+ if (!EnsureCapacity(buffer_length)) {
+ buffer_length = capacity_ - length_ - 1; // Copy what fits.
+ }
+ memmove(&buffer_[length_], buffer, buffer_length);
+ length_ += buffer_length;
+ buffer_[length_] = '\0';
+}
+
// Write a UTF-32 code unit so it can be read by a JSON parser in a string
// literal. Use official encoding from JSON specification. http://json.org/
-void TextBuffer::EscapeAndAddCodeUnit(uint32_t codeunit) {
+void BaseTextBuffer::EscapeAndAddCodeUnit(uint32_t codeunit) {
switch (codeunit) {
case '"':
AddRaw(reinterpret_cast<uint8_t const*>("\\\""), 2);
@@ -117,49 +96,56 @@
// Write an incomplete UTF-16 code unit so it can be read by a JSON parser in a
// string literal.
-void TextBuffer::EscapeAndAddUTF16CodeUnit(uint16_t codeunit) {
+void BaseTextBuffer::EscapeAndAddUTF16CodeUnit(uint16_t codeunit) {
Printf("\\u%04X", codeunit);
}
-void TextBuffer::AddString(const char* s) {
+void BaseTextBuffer::AddString(const char* s) {
Printf("%s", s);
}
-void TextBuffer::AddEscapedString(const char* s) {
+void BaseTextBuffer::AddEscapedString(const char* s) {
intptr_t len = strlen(s);
for (int i = 0; i < len; i++) {
EscapeAndAddCodeUnit(s[i]);
}
}
-void TextBuffer::EnsureCapacity(intptr_t len) {
- intptr_t remaining = buf_size_ - msg_len_;
+TextBuffer::TextBuffer(intptr_t buf_size) {
+ ASSERT(buf_size > 0);
+ buffer_ = reinterpret_cast<char*>(malloc(buf_size));
+ if (buffer_ == nullptr) {
+ OUT_OF_MEMORY();
+ }
+ capacity_ = buf_size;
+ Clear();
+}
+
+TextBuffer::~TextBuffer() {
+ free(buffer_);
+ buffer_ = nullptr;
+}
+
+char* TextBuffer::Steal() {
+ char* r = buffer_;
+ buffer_ = nullptr;
+ capacity_ = 0;
+ length_ = 0;
+ return r;
+}
+
+bool TextBuffer::EnsureCapacity(intptr_t len) {
+ intptr_t remaining = capacity_ - length_;
if (remaining <= len) {
- intptr_t new_size = buf_size_ + Utils::Maximum(buf_size_, len + 1);
- char* new_buf = reinterpret_cast<char*>(realloc(buf_, new_size));
- if (new_buf == NULL) {
+ intptr_t new_size = capacity_ + Utils::Maximum(capacity_, len + 1);
+ char* new_buf = reinterpret_cast<char*>(realloc(buffer_, new_size));
+ if (new_buf == nullptr) {
OUT_OF_MEMORY();
}
- buf_ = new_buf;
- buf_size_ = new_size;
+ buffer_ = new_buf;
+ capacity_ = new_size;
}
-}
-
-void BufferFormatter::Print(const char* format, ...) {
- va_list args;
- va_start(args, format);
- VPrint(format, args);
- va_end(args);
-}
-
-void BufferFormatter::VPrint(const char* format, va_list args) {
- intptr_t available = size_ - position_;
- if (available <= 0) return;
- intptr_t written =
- Utils::VSNPrint(buffer_ + position_, available, format, args);
- if (written >= 0) {
- position_ += (available <= written) ? available : written;
- }
+ return true;
}
} // namespace dart
diff --git a/runtime/platform/text_buffer.h b/runtime/platform/text_buffer.h
index 23deeed..c44d955 100644
--- a/runtime/platform/text_buffer.h
+++ b/runtime/platform/text_buffer.h
@@ -10,12 +10,14 @@
namespace dart {
-// TextBuffer maintains a dynamic character buffer with a printf-style way to
-// append text.
-class TextBuffer : ValueObject {
+// BaseTextBuffer maintains a dynamic character buffer with a printf-style way
+// to append text. Internal buffer management is handled by subclasses.
+class BaseTextBuffer : public ValueObject {
public:
- explicit TextBuffer(intptr_t buf_size);
- ~TextBuffer();
+ BaseTextBuffer() : buffer_(nullptr), capacity_(0), length_(0) {}
+ BaseTextBuffer(char* buffer, intptr_t capacity)
+ : buffer_(buffer), capacity_(capacity), length_(0) {}
+ virtual ~BaseTextBuffer() {}
intptr_t Printf(const char* format, ...) PRINTF_ATTRIBUTE(2, 3);
void AddChar(char ch);
@@ -25,39 +27,67 @@
void AddEscapedString(const char* s);
void AddRaw(const uint8_t* buffer, intptr_t buffer_length);
- void Clear();
+ // Returns a pointer to the current internal buffer. Whether the pointer is
+ // still valid after the BaseTextBuffer dies depends on the subclass.
+ char* buffer() const { return buffer_; }
+ intptr_t length() const { return length_; }
- char* buf() { return buf_; }
- intptr_t length() { return msg_len_; }
+ // Clears the stored contents. Unless specified otherwise by the subclass,
+ // should be assumed to invalidate the contents of previous calls to buffer().
+ virtual void Clear() = 0;
+
+ protected:
+ virtual bool EnsureCapacity(intptr_t len) = 0;
+
+ char* buffer_;
+ intptr_t capacity_;
+ intptr_t length_;
+
+ DISALLOW_COPY_AND_ASSIGN(BaseTextBuffer);
+};
+
+// TextBuffer uses manual memory management for the character buffer. Unless
+// Steal() is used, the internal buffer is deallocated when the object dies.
+class TextBuffer : public BaseTextBuffer {
+ public:
+ explicit TextBuffer(intptr_t buf_size);
+ ~TextBuffer();
+
+ // Resets the contents of the internal buffer.
+ void Clear() { set_length(0); }
+
void set_length(intptr_t len) {
ASSERT(len >= 0);
- ASSERT(len <= msg_len_);
- msg_len_ = len;
+ ASSERT(len <= length_);
+ length_ = len;
+ buffer_[len] = '\0';
}
- // Steal ownership of the buffer pointer.
+ // Take ownership of the buffer contents. Future uses of the TextBuffer object
+ // will not affect the contents of the returned buffer.
// NOTE: TextBuffer is empty afterwards.
char* Steal();
private:
- void EnsureCapacity(intptr_t len);
- char* buf_;
- intptr_t buf_size_;
- intptr_t msg_len_;
+ bool EnsureCapacity(intptr_t len);
+
+ DISALLOW_COPY_AND_ASSIGN(TextBuffer);
};
-class BufferFormatter : public ValueObject {
+class BufferFormatter : public BaseTextBuffer {
public:
- BufferFormatter(char* buffer, intptr_t size)
- : position_(0), buffer_(buffer), size_(size) {}
+ BufferFormatter(char* buffer, intptr_t size) : BaseTextBuffer(buffer, size) {
+ buffer_[length_] = '\0';
+ }
- void VPrint(const char* format, va_list args);
- void Print(const char* format, ...) PRINTF_ATTRIBUTE(2, 3);
+ void Clear() {
+ length_ = 0;
+ buffer_[length_] = '\0';
+ }
private:
- intptr_t position_;
- char* buffer_;
- const intptr_t size_;
+ // We can't extend, so only return true if there's room.
+ bool EnsureCapacity(intptr_t len) { return length_ + len <= capacity_ - 1; }
DISALLOW_COPY_AND_ASSIGN(BufferFormatter);
};
diff --git a/runtime/tests/vm/dart/b162922506_test.dart b/runtime/tests/vm/dart/b162922506_test.dart
new file mode 100644
index 0000000..bb7d8b7
--- /dev/null
+++ b/runtime/tests/vm/dart/b162922506_test.dart
@@ -0,0 +1,79 @@
+// Copyright (c) 2020, 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.
+
+// Regression test for b/162922506: verify that compiler does not use signed
+// 16-bit integers to store class ids for slots.
+
+import 'dart:io';
+
+import 'package:expect/expect.dart';
+import 'package:path/path.dart' as p;
+
+void main() async {
+ Directory tmp = await Directory.systemTemp.createTemp("b162922506");
+ File testBody = File(p.join(tmp.path, 'test.dart'));
+ try {
+ generateTestBody(testBody);
+ final result = await Process.run(Platform.executable, [
+ ...Platform.executableArguments,
+ '--deterministic',
+ '--optimization-counter-threshold=10',
+ '--no-use-osr',
+ testBody.path
+ ]);
+ if (result.exitCode != 0) {
+ print('''
+Subprocess output:
+${result.stdout}
+${result.stderr}
+''');
+ }
+ Expect.equals(0, result.exitCode);
+ Expect.equals("OK", (result.stdout as String).trim());
+ } finally {
+ await tmp.delete(recursive: true);
+ }
+}
+
+void generateTestBody(File testBody) {
+ final sb = StringBuffer();
+
+ sb.write("""
+import 'package:expect/expect.dart';
+""");
+ final n = 0x8010;
+ for (var i = 0; i < n; i++) {
+ sb.write("""
+class C$i {
+ final f;
+ C$i(this.f);
+
+""");
+ if (i == (n - 1)) {
+ sb.write("""
+ test({bool rareCase: false}) {
+ final v = this.f;
+ if (rareCase) {
+ return v.f;
+ }
+ return null;
+ }
+""");
+ }
+ sb.write("""
+
+}
+""");
+ }
+ sb.write("""
+void main() {
+ final obj = C${n - 1}(C${n - 2}(C${n - 3}(null)));
+ for (var i = 0; i < 100; i++) obj.test();
+ Expect.isTrue(obj.test(rareCase: true) is C${n - 3});
+ print("OK");
+}
+ """);
+
+ testBody.writeAsStringSync(sb.toString());
+}
diff --git a/runtime/tests/vm/dart_2/b162922506_test.dart b/runtime/tests/vm/dart_2/b162922506_test.dart
new file mode 100644
index 0000000..bb7d8b7
--- /dev/null
+++ b/runtime/tests/vm/dart_2/b162922506_test.dart
@@ -0,0 +1,79 @@
+// Copyright (c) 2020, 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.
+
+// Regression test for b/162922506: verify that compiler does not use signed
+// 16-bit integers to store class ids for slots.
+
+import 'dart:io';
+
+import 'package:expect/expect.dart';
+import 'package:path/path.dart' as p;
+
+void main() async {
+ Directory tmp = await Directory.systemTemp.createTemp("b162922506");
+ File testBody = File(p.join(tmp.path, 'test.dart'));
+ try {
+ generateTestBody(testBody);
+ final result = await Process.run(Platform.executable, [
+ ...Platform.executableArguments,
+ '--deterministic',
+ '--optimization-counter-threshold=10',
+ '--no-use-osr',
+ testBody.path
+ ]);
+ if (result.exitCode != 0) {
+ print('''
+Subprocess output:
+${result.stdout}
+${result.stderr}
+''');
+ }
+ Expect.equals(0, result.exitCode);
+ Expect.equals("OK", (result.stdout as String).trim());
+ } finally {
+ await tmp.delete(recursive: true);
+ }
+}
+
+void generateTestBody(File testBody) {
+ final sb = StringBuffer();
+
+ sb.write("""
+import 'package:expect/expect.dart';
+""");
+ final n = 0x8010;
+ for (var i = 0; i < n; i++) {
+ sb.write("""
+class C$i {
+ final f;
+ C$i(this.f);
+
+""");
+ if (i == (n - 1)) {
+ sb.write("""
+ test({bool rareCase: false}) {
+ final v = this.f;
+ if (rareCase) {
+ return v.f;
+ }
+ return null;
+ }
+""");
+ }
+ sb.write("""
+
+}
+""");
+ }
+ sb.write("""
+void main() {
+ final obj = C${n - 1}(C${n - 2}(C${n - 3}(null)));
+ for (var i = 0; i < 100; i++) obj.test();
+ Expect.isTrue(obj.test(rareCase: true) is C${n - 3});
+ print("OK");
+}
+ """);
+
+ testBody.writeAsStringSync(sb.toString());
+}
diff --git a/runtime/tests/vm/vm.status b/runtime/tests/vm/vm.status
index 13c1e72..7f379ab 100644
--- a/runtime/tests/vm/vm.status
+++ b/runtime/tests/vm/vm.status
@@ -79,6 +79,10 @@
dart_2/redirection_type_shuffling_test/none: RuntimeError
dart_2/snapshot_version_test: RuntimeError
+[ $compiler != dartk ]
+dart/b162922506_test: SkipByDesign # Only run in JIT
+dart_2/b162922506_test: SkipByDesign # Only run in JIT
+
[ $compiler == dartkb ]
dart/generic_field_invocation_test: SkipByDesign # KBC interpreters do not support --no_lazy_dispatchers
dart_2/generic_field_invocation_test: SkipByDesign # KBC interpreters do not support --no_lazy_dispatchers
@@ -112,11 +116,13 @@
cc/VerifyExplicit_Crash: Crash # Negative tests of VerifiedMemory should crash iff in DEBUG mode. TODO(koda): Improve support for negative tests.
cc/VerifyImplicit_Crash: Crash # Negative tests of VerifiedMemory should crash iff in DEBUG mode. TODO(koda): Improve support for negative tests.
dart/appjit_cha_deopt_test: Pass, Slow # Quite slow in debug mode, uses --optimization-counter-threshold=100
+dart/b162922506_test: SkipSlow # Generates very large input file
dart/minimal_kernel_bytecode_test: SkipSlow # gen_kernel is too slow in debug mode
dart/minimal_kernel_test: SkipSlow # gen_kernel is too slow in debug mode
dart/null_safety_autodetection_in_kernel_compiler_test: SkipSlow # gen_kernel is too slow in debug mode
dart/spawn_shutdown_test: Pass, Slow # VM Shutdown test, It can take some time for all the isolates to shutdown in a Debug build.
dart_2/appjit_cha_deopt_test: Pass, Slow # Quite slow in debug mode, uses --optimization-counter-threshold=100
+dart_2/b162922506_test: SkipSlow # Generates very large input file
dart_2/minimal_kernel_bytecode_test: SkipSlow # gen_kernel is too slow in debug mode
dart_2/minimal_kernel_test: SkipSlow # gen_kernel is too slow in debug mode
dart_2/null_safety_autodetection_in_kernel_compiler_test: SkipSlow # gen_kernel is too slow in debug mode
@@ -284,12 +290,14 @@
[ ($arch == simarm || $arch == simarm64) && ($compiler == dartk || $compiler == dartkb) ]
dart/appjit*: SkipSlow # DFE too slow
+dart/b162922506_test: SkipSlow # Generates large input file
dart/data_uri_spawn_test: Skip # Please triage.
dart/minimal_kernel_bytecode_test: SkipSlow # gen_kernel is too slow on simulated architectures
dart/minimal_kernel_test: SkipSlow # gen_kernel is too slow on simulated architectures
dart/null_safety_autodetection_in_kernel_compiler_test: SkipSlow # gen_kernel is too slow on simulated architectures
dart/snapshot_version_test: RuntimeError # Please triage.
dart_2/appjit*: SkipSlow # DFE too slow
+dart_2/b162922506_test: SkipSlow # Generates large input file
dart_2/data_uri_spawn_test: Skip # Please triage.
dart_2/minimal_kernel_bytecode_test: SkipSlow # gen_kernel is too slow on simulated architectures
dart_2/minimal_kernel_test: SkipSlow # gen_kernel is too slow on simulated architectures
diff --git a/runtime/vm/class_id.h b/runtime/vm/class_id.h
index f943cc4..0664cbb 100644
--- a/runtime/vm/class_id.h
+++ b/runtime/vm/class_id.h
@@ -14,6 +14,9 @@
namespace dart {
+// Size of the class-id part of the object header. See ObjectLayout.
+typedef uint16_t ClassIdTagType;
+
#define CLASS_LIST_NO_OBJECT_NOR_STRING_NOR_ARRAY(V) \
V(Class) \
V(PatchClass) \
diff --git a/runtime/vm/code_descriptors.cc b/runtime/vm/code_descriptors.cc
index aaaa159..a462905 100644
--- a/runtime/vm/code_descriptors.cc
+++ b/runtime/vm/code_descriptors.cc
@@ -271,7 +271,7 @@
list_[i].is_generated);
handlers.SetHandledTypes(i, Array::empty_array());
} else {
- const bool has_catch_all = ContainsDynamic(*list_[i].handler_types);
+ const bool has_catch_all = ContainsCatchAllType(*list_[i].handler_types);
handlers.SetHandlerInfo(i, list_[i].outer_try_index, list_[i].pc_offset,
list_[i].needs_stacktrace, has_catch_all,
list_[i].is_generated);
diff --git a/runtime/vm/code_descriptors.h b/runtime/vm/code_descriptors.h
index 8b74bde..6f89c91 100644
--- a/runtime/vm/code_descriptors.h
+++ b/runtime/vm/code_descriptors.h
@@ -190,9 +190,11 @@
list_[try_index].needs_stacktrace = true;
}
- static bool ContainsDynamic(const Array& array) {
+ static bool ContainsCatchAllType(const Array& array) {
+ auto& type = AbstractType::Handle();
for (intptr_t i = 0; i < array.Length(); i++) {
- if (array.At(i) == Type::DynamicType()) {
+ type ^= array.At(i);
+ if (type.IsCatchAllType()) {
return true;
}
}
diff --git a/runtime/vm/compiler/aot/dispatch_table_generator.cc b/runtime/vm/compiler/aot/dispatch_table_generator.cc
index af7a1e1..073a227 100644
--- a/runtime/vm/compiler/aot/dispatch_table_generator.cc
+++ b/runtime/vm/compiler/aot/dispatch_table_generator.cc
@@ -420,8 +420,12 @@
const auto& info = KernelProgramInfo::Handle(Z, script.kernel_program_info());
kernel::TableSelectorMetadata* metadata =
kernel::TableSelectorMetadataForProgram(info, Z);
- // This assert will fail if gen_kernel was run in non-AOT mode or without TFA.
- RELEASE_ASSERT(metadata != nullptr);
+ // Errors out if gen_kernel was run in non-AOT mode or without TFA.
+ if (metadata == nullptr) {
+ FATAL(
+ "Missing table selector metadata!\n"
+ "Probably gen_kernel was run in non-AOT mode or without TFA.\n");
+ }
for (intptr_t i = 0; i < metadata->selectors.length(); i++) {
const kernel::TableSelectorInfo* info = &metadata->selectors[i];
selector_map_.AddSelector(info->call_count, info->called_on_null,
diff --git a/runtime/vm/compiler/assembler/disassembler.cc b/runtime/vm/compiler/assembler/disassembler.cc
index 522e505..2d1515f 100644
--- a/runtime/vm/compiler/assembler/disassembler.cc
+++ b/runtime/vm/compiler/assembler/disassembler.cc
@@ -191,14 +191,14 @@
for (intptr_t i = 1; i < inlined_functions.length(); i++) {
const char* name = inlined_functions[i]->ToQualifiedCString();
if (first) {
- f.Print(" ;; Inlined [%s", name);
+ f.Printf(" ;; Inlined [%s", name);
first = false;
} else {
- f.Print(" -> %s", name);
+ f.Printf(" -> %s", name);
}
}
if (!first) {
- f.Print("]\n");
+ f.AddString("]\n");
formatter->Print("%s", str);
}
}
diff --git a/runtime/vm/compiler/backend/compile_type.h b/runtime/vm/compiler/backend/compile_type.h
index 32c9949..3a7d6aa 100644
--- a/runtime/vm/compiler/backend/compile_type.h
+++ b/runtime/vm/compiler/backend/compile_type.h
@@ -16,7 +16,7 @@
namespace dart {
class AbstractType;
-class BufferFormatter;
+class BaseTextBuffer;
class Definition;
class FlowGraphSerializer;
class SExpression;
@@ -247,7 +247,7 @@
bool Specialize(GrowableArray<intptr_t>* class_ids);
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
SExpression* ToSExpression(FlowGraphSerializer* s) const;
void AddExtraInfoToSExpression(SExpList* sexp, FlowGraphSerializer* s) const;
diff --git a/runtime/vm/compiler/backend/flow_graph.cc b/runtime/vm/compiler/backend/flow_graph.cc
index c285c51..5890545 100644
--- a/runtime/vm/compiler/backend/flow_graph.cc
+++ b/runtime/vm/compiler/backend/flow_graph.cc
@@ -1295,6 +1295,14 @@
// Trim extra inputs of ClosureCall and LoadField instructions from
// the environment. Inputs of those instructions are not pushed onto
// the stack at the point where deoptimization can occur.
+ // Note that in case of LoadField there can be two possible situations,
+ // the code here handles LoadField to LoadField lazy deoptimization in
+ // which we are transitioning from position after the call to initialization
+ // stub in optimized code to a similar position after the call to
+ // initialization stub in unoptimized code. There is another variant
+ // (LoadField deoptimizing into a position after a getter call) which is
+ // handled in a different way (see
+ // CallSpecializer::InlineImplicitInstanceGetter).
deopt_env =
deopt_env->DeepCopy(zone(), deopt_env->Length() - instr->InputCount() +
instr->ArgumentCount());
diff --git a/runtime/vm/compiler/backend/il.h b/runtime/vm/compiler/backend/il.h
index 8c76dad..8b3cc81 100644
--- a/runtime/vm/compiler/backend/il.h
+++ b/runtime/vm/compiler/backend/il.h
@@ -35,12 +35,12 @@
namespace dart {
+class BaseTextBuffer;
class BinaryFeedback;
class BitVector;
class BlockEntryInstr;
class BlockEntryWithInitialDefs;
class BoxIntegerInstr;
-class BufferFormatter;
class CallTargets;
class CatchBlockEntryInstr;
class CheckBoundBase;
@@ -145,7 +145,7 @@
void RefineReachingType(CompileType* type);
#if !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
SExpression* ToSExpression(FlowGraphSerializer* s) const;
@@ -550,14 +550,14 @@
DECLARE_COMPARISON_METHODS
#if !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
-#define PRINT_TO_SUPPORT virtual void PrintTo(BufferFormatter* f) const;
+#define PRINT_TO_SUPPORT virtual void PrintTo(BaseTextBuffer* f) const;
#else
#define PRINT_TO_SUPPORT
#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
#if !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
#define PRINT_OPERANDS_TO_SUPPORT \
- virtual void PrintOperandsTo(BufferFormatter* f) const;
+ virtual void PrintOperandsTo(BaseTextBuffer* f) const;
#else
#define PRINT_OPERANDS_TO_SUPPORT
#endif // !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
@@ -911,8 +911,8 @@
// Printing support.
const char* ToCString() const;
#if !defined(PRODUCT) || defined(FORCE_INCLUDE_DISASSEMBLER)
- virtual void PrintTo(BufferFormatter* f) const;
- virtual void PrintOperandsTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
+ virtual void PrintOperandsTo(BaseTextBuffer* f) const;
#endif
virtual SExpression* ToSExpression(FlowGraphSerializer* s) const;
virtual void AddOperandsToSExpression(SExpList* sexp,
@@ -1614,7 +1614,7 @@
}
protected:
- void PrintInitialDefinitionsTo(BufferFormatter* f) const;
+ void PrintInitialDefinitionsTo(BaseTextBuffer* f) const;
private:
GrowableArray<Definition*> initial_definitions_;
@@ -5864,7 +5864,7 @@
virtual bool HasUnknownSideEffects() const { return false; }
- void PrintOperandsTo(BufferFormatter* f) const;
+ void PrintOperandsTo(BaseTextBuffer* f) const;
virtual Instruction* Canonicalize(FlowGraph* flow_graph);
@@ -9330,7 +9330,7 @@
Definition* dead,
Definition* result) const;
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
SExpression* ToSExpression(FlowGraphSerializer* s) const;
const char* ToCString() const;
diff --git a/runtime/vm/compiler/backend/il_deserializer.cc b/runtime/vm/compiler/backend/il_deserializer.cc
index 30d4520..ca7bd32 100644
--- a/runtime/vm/compiler/backend/il_deserializer.cc
+++ b/runtime/vm/compiler/backend/il_deserializer.cc
@@ -102,7 +102,7 @@
if (results.serialized != nullptr) {
TextBuffer buf(1000);
results.serialized->SerializeTo(zone, &buf, "");
- js.PrintProperty("serialized", buf.buf());
+ js.PrintProperty("serialized", buf.buffer());
}
if (results.error_message != nullptr) {
@@ -112,7 +112,7 @@
ASSERT(results.error_sexp != nullptr);
TextBuffer buf(1000);
results.error_sexp->SerializeTo(zone, &buf, "");
- js.PrintProperty("expression", buf.buf());
+ js.PrintProperty("expression", buf.buffer());
auto const sexp_position =
GetSExpressionPosition(zone, results.serialized, results.error_sexp);
@@ -121,7 +121,7 @@
}
js.CloseObject();
- THR_Print("Results of round trip serialization: %s\n", js.buffer()->buf());
+ THR_Print("Results of round trip serialization: %s\n", js.buffer()->buffer());
}
void FlowGraphDeserializer::RoundTripSerialization(CompilerPassState* state) {
@@ -159,7 +159,7 @@
if (FLAG_trace_round_trip_serialization && results.serialized != nullptr) {
TextBuffer buf(1000);
results.serialized->SerializeTo(zone, &buf, "");
- THR_Print("Serialized flow graph:\n%s\n", buf.buf());
+ THR_Print("Serialized flow graph:\n%s\n", buf.buffer());
}
// For the deserializer, use the thread from the compiler pass and zone
diff --git a/runtime/vm/compiler/backend/il_printer.cc b/runtime/vm/compiler/backend/il_printer.cc
index a1289a9..b326057 100644
--- a/runtime/vm/compiler/backend/il_printer.cc
+++ b/runtime/vm/compiler/backend/il_printer.cc
@@ -103,11 +103,11 @@
String::Handle(dst_type.Name()).ToCString(), dst_name.ToCString());
}
-static void PrintTargetsHelper(BufferFormatter* f,
+static void PrintTargetsHelper(BaseTextBuffer* f,
const CallTargets& targets,
intptr_t num_checks_to_print) {
- f->Print(" Targets[");
- f->Print("%" Pd ": ", targets.length());
+ f->AddString(" Targets[");
+ f->Printf("%" Pd ": ", targets.length());
Function& target = Function::Handle();
if ((num_checks_to_print == FlowGraphPrinter::kPrintAll) ||
(num_checks_to_print > targets.length())) {
@@ -119,36 +119,36 @@
const intptr_t count = target_info->count;
target = target_info->target->raw();
if (i > 0) {
- f->Print(" | ");
+ f->AddString(" | ");
}
if (range.IsSingleCid()) {
const Class& cls =
Class::Handle(Isolate::Current()->class_table()->At(range.cid_start));
- f->Print("%s", String::Handle(cls.Name()).ToCString());
- f->Print(" cid %" Pd " cnt:%" Pd " trgt:'%s'", range.cid_start, count,
- target.ToQualifiedCString());
+ f->Printf("%s", String::Handle(cls.Name()).ToCString());
+ f->Printf(" cid %" Pd " cnt:%" Pd " trgt:'%s'", range.cid_start, count,
+ target.ToQualifiedCString());
} else {
const Class& cls = Class::Handle(target.Owner());
- f->Print("cid %" Pd "-%" Pd " %s", range.cid_start, range.cid_end,
- String::Handle(cls.Name()).ToCString());
- f->Print(" cnt:%" Pd " trgt:'%s'", count, target.ToQualifiedCString());
+ f->Printf("cid %" Pd "-%" Pd " %s", range.cid_start, range.cid_end,
+ String::Handle(cls.Name()).ToCString());
+ f->Printf(" cnt:%" Pd " trgt:'%s'", count, target.ToQualifiedCString());
}
if (target_info->exactness.IsTracking()) {
- f->Print(" %s", target_info->exactness.ToCString());
+ f->Printf(" %s", target_info->exactness.ToCString());
}
}
if (num_checks_to_print < targets.length()) {
- f->Print("...");
+ f->AddString("...");
}
- f->Print("]");
+ f->AddString("]");
}
-static void PrintCidsHelper(BufferFormatter* f,
+static void PrintCidsHelper(BaseTextBuffer* f,
const Cids& targets,
intptr_t num_checks_to_print) {
- f->Print(" Cids[");
- f->Print("%" Pd ": ", targets.length());
+ f->AddString(" Cids[");
+ f->Printf("%" Pd ": ", targets.length());
if ((num_checks_to_print == FlowGraphPrinter::kPrintAll) ||
(num_checks_to_print > targets.length())) {
num_checks_to_print = targets.length();
@@ -156,32 +156,33 @@
for (intptr_t i = 0; i < num_checks_to_print; i++) {
const CidRange& range = targets[i];
if (i > 0) {
- f->Print(" | ");
+ f->AddString(" | ");
}
const Class& cls =
Class::Handle(Isolate::Current()->class_table()->At(range.cid_start));
- f->Print("%s etc. ", String::Handle(cls.Name()).ToCString());
+ f->Printf("%s etc. ", String::Handle(cls.Name()).ToCString());
if (range.IsSingleCid()) {
- f->Print(" cid %" Pd, range.cid_start);
+ f->Printf(" cid %" Pd, range.cid_start);
} else {
- f->Print(" cid %" Pd "-%" Pd, range.cid_start, range.cid_end);
+ f->Printf(" cid %" Pd "-%" Pd, range.cid_start, range.cid_end);
}
}
if (num_checks_to_print < targets.length()) {
- f->Print("...");
+ f->AddString("...");
}
- f->Print("]");
+ f->AddString("]");
}
-static void PrintICDataHelper(BufferFormatter* f,
+static void PrintICDataHelper(BaseTextBuffer* f,
const ICData& ic_data,
intptr_t num_checks_to_print) {
- f->Print(" IC[");
+ f->AddString(" IC[");
if (ic_data.is_tracking_exactness()) {
- f->Print("(%s) ",
- AbstractType::Handle(ic_data.receivers_static_type()).ToCString());
+ f->Printf(
+ "(%s) ",
+ AbstractType::Handle(ic_data.receivers_static_type()).ToCString());
}
- f->Print("%" Pd ": ", ic_data.NumberOfChecks());
+ f->Printf("%" Pd ": ", ic_data.NumberOfChecks());
Function& target = Function::Handle();
if ((num_checks_to_print == FlowGraphPrinter::kPrintAll) ||
(num_checks_to_print > ic_data.NumberOfChecks())) {
@@ -192,40 +193,40 @@
ic_data.GetCheckAt(i, &class_ids, &target);
const intptr_t count = ic_data.GetCountAt(i);
if (i > 0) {
- f->Print(" | ");
+ f->AddString(" | ");
}
for (intptr_t k = 0; k < class_ids.length(); k++) {
if (k > 0) {
- f->Print(", ");
+ f->AddString(", ");
}
const Class& cls =
Class::Handle(Isolate::Current()->class_table()->At(class_ids[k]));
- f->Print("%s", String::Handle(cls.Name()).ToCString());
+ f->Printf("%s", String::Handle(cls.Name()).ToCString());
}
- f->Print(" cnt:%" Pd " trgt:'%s'", count, target.ToQualifiedCString());
+ f->Printf(" cnt:%" Pd " trgt:'%s'", count, target.ToQualifiedCString());
if (ic_data.is_tracking_exactness()) {
- f->Print(" %s", ic_data.GetExactnessAt(i).ToCString());
+ f->Printf(" %s", ic_data.GetExactnessAt(i).ToCString());
}
}
if (num_checks_to_print < ic_data.NumberOfChecks()) {
- f->Print("...");
+ f->AddString("...");
}
- f->Print("]");
+ f->AddString("]");
}
-static void PrintICDataSortedHelper(BufferFormatter* f,
+static void PrintICDataSortedHelper(BaseTextBuffer* f,
const ICData& ic_data_orig) {
const ICData& ic_data =
ICData::Handle(ic_data_orig.AsUnaryClassChecksSortedByCount());
- f->Print(" IC[n:%" Pd "; ", ic_data.NumberOfChecks());
+ f->Printf(" IC[n:%" Pd "; ", ic_data.NumberOfChecks());
for (intptr_t i = 0; i < ic_data.NumberOfChecks(); i++) {
const intptr_t count = ic_data.GetCountAt(i);
const intptr_t cid = ic_data.GetReceiverClassIdAt(i);
const Class& cls =
Class::Handle(Isolate::Current()->class_table()->At(cid));
- f->Print("%s : %" Pd ", ", String::Handle(cls.Name()).ToCString(), count);
+ f->Printf("%s : %" Pd ", ", String::Handle(cls.Name()).ToCString(), count);
}
- f->Print("]");
+ f->AddString("]");
}
void FlowGraphPrinter::PrintICData(const ICData& ic_data,
@@ -247,16 +248,16 @@
// TODO(erikcorry): Print args descriptor.
}
-static void PrintUse(BufferFormatter* f, const Definition& definition) {
+static void PrintUse(BaseTextBuffer* f, const Definition& definition) {
if (definition.HasSSATemp()) {
if (definition.HasPairRepresentation()) {
- f->Print("(v%" Pd ", v%" Pd ")", definition.ssa_temp_index(),
- definition.ssa_temp_index() + 1);
+ f->Printf("(v%" Pd ", v%" Pd ")", definition.ssa_temp_index(),
+ definition.ssa_temp_index() + 1);
} else {
- f->Print("v%" Pd "", definition.ssa_temp_index());
+ f->Printf("v%" Pd "", definition.ssa_temp_index());
}
} else if (definition.HasTemp()) {
- f->Print("t%" Pd "", definition.temp_index());
+ f->Printf("t%" Pd "", definition.temp_index());
}
}
@@ -267,114 +268,114 @@
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
-void Instruction::PrintTo(BufferFormatter* f) const {
+void Instruction::PrintTo(BaseTextBuffer* f) const {
if (GetDeoptId() != DeoptId::kNone) {
- f->Print("%s:%" Pd "(", DebugName(), GetDeoptId());
+ f->Printf("%s:%" Pd "(", DebugName(), GetDeoptId());
} else {
- f->Print("%s(", DebugName());
+ f->Printf("%s(", DebugName());
}
PrintOperandsTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void Instruction::PrintOperandsTo(BufferFormatter* f) const {
+void Instruction::PrintOperandsTo(BaseTextBuffer* f) const {
for (int i = 0; i < InputCount(); ++i) {
- if (i > 0) f->Print(", ");
+ if (i > 0) f->AddString(", ");
if (InputAt(i) != NULL) InputAt(i)->PrintTo(f);
}
}
-void Definition::PrintTo(BufferFormatter* f) const {
+void Definition::PrintTo(BaseTextBuffer* f) const {
PrintUse(f, *this);
- if (HasSSATemp() || HasTemp()) f->Print(" <- ");
+ if (HasSSATemp() || HasTemp()) f->AddString(" <- ");
if (GetDeoptId() != DeoptId::kNone) {
- f->Print("%s:%" Pd "(", DebugName(), GetDeoptId());
+ f->Printf("%s:%" Pd "(", DebugName(), GetDeoptId());
} else {
- f->Print("%s(", DebugName());
+ f->Printf("%s(", DebugName());
}
PrintOperandsTo(f);
- f->Print(")");
+ f->AddString(")");
if (range_ != NULL) {
- f->Print(" ");
+ f->AddString(" ");
range_->PrintTo(f);
}
if (type_ != NULL) {
- f->Print(" ");
+ f->AddString(" ");
type_->PrintTo(f);
}
}
-void CheckNullInstr::PrintOperandsTo(BufferFormatter* f) const {
+void CheckNullInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Definition::PrintOperandsTo(f);
switch (exception_type()) {
case kNoSuchMethod:
- f->Print(", NoSuchMethodError");
+ f->AddString(", NoSuchMethodError");
break;
case kArgumentError:
- f->Print(", ArgumentError");
+ f->AddString(", ArgumentError");
break;
case kCastError:
- f->Print(", CastError");
+ f->AddString(", CastError");
break;
}
}
-void Definition::PrintOperandsTo(BufferFormatter* f) const {
+void Definition::PrintOperandsTo(BaseTextBuffer* f) const {
for (int i = 0; i < InputCount(); ++i) {
- if (i > 0) f->Print(", ");
+ if (i > 0) f->AddString(", ");
if (InputAt(i) != NULL) {
InputAt(i)->PrintTo(f);
}
}
}
-void RedefinitionInstr::PrintOperandsTo(BufferFormatter* f) const {
+void RedefinitionInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Definition::PrintOperandsTo(f);
if (constrained_type_ != nullptr) {
- f->Print(" ^ %s", constrained_type_->ToCString());
+ f->Printf(" ^ %s", constrained_type_->ToCString());
}
}
-void ReachabilityFenceInstr::PrintOperandsTo(BufferFormatter* f) const {
+void ReachabilityFenceInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
}
-void Value::PrintTo(BufferFormatter* f) const {
+void Value::PrintTo(BaseTextBuffer* f) const {
PrintUse(f, *definition());
if ((reaching_type_ != NULL) && (reaching_type_ != definition()->type_)) {
- f->Print(" ");
+ f->AddString(" ");
reaching_type_->PrintTo(f);
}
}
-void ConstantInstr::PrintOperandsTo(BufferFormatter* f) const {
+void ConstantInstr::PrintOperandsTo(BaseTextBuffer* f) const {
const char* cstr = value().ToCString();
const char* new_line = strchr(cstr, '\n');
if (new_line == NULL) {
- f->Print("#%s", cstr);
+ f->Printf("#%s", cstr);
} else {
const intptr_t pos = new_line - cstr;
char* buffer = Thread::Current()->zone()->Alloc<char>(pos + 1);
strncpy(buffer, cstr, pos);
buffer[pos] = '\0';
- f->Print("#%s\\n...", buffer);
+ f->Printf("#%s\\n...", buffer);
}
}
-void ConstraintInstr::PrintOperandsTo(BufferFormatter* f) const {
+void ConstraintInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
- f->Print(" ^ ");
+ f->AddString(" ^ ");
constraint()->PrintTo(f);
}
-void Range::PrintTo(BufferFormatter* f) const {
- f->Print("[");
+void Range::PrintTo(BaseTextBuffer* f) const {
+ f->AddString("[");
min_.PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
max_.PrintTo(f);
- f->Print("]");
+ f->AddString("]");
}
const char* Range::ToCString(const Range* range) {
@@ -386,24 +387,24 @@
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
-void RangeBoundary::PrintTo(BufferFormatter* f) const {
+void RangeBoundary::PrintTo(BaseTextBuffer* f) const {
switch (kind_) {
case kSymbol:
- f->Print("v%" Pd "",
- reinterpret_cast<Definition*>(value_)->ssa_temp_index());
- if (offset_ != 0) f->Print("%+" Pd64 "", offset_);
+ f->Printf("v%" Pd "",
+ reinterpret_cast<Definition*>(value_)->ssa_temp_index());
+ if (offset_ != 0) f->Printf("%+" Pd64 "", offset_);
break;
case kNegativeInfinity:
- f->Print("-inf");
+ f->AddString("-inf");
break;
case kPositiveInfinity:
- f->Print("+inf");
+ f->AddString("+inf");
break;
case kConstant:
- f->Print("%" Pd64 "", value_);
+ f->Printf("%" Pd64 "", value_);
break;
case kUnknown:
- f->Print("_|_");
+ f->AddString("_|_");
break;
}
}
@@ -415,61 +416,61 @@
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
-void MakeTempInstr::PrintOperandsTo(BufferFormatter* f) const {}
+void MakeTempInstr::PrintOperandsTo(BaseTextBuffer* f) const {}
-void DropTempsInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%" Pd "", num_temps());
+void DropTempsInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%" Pd "", num_temps());
if (value() != NULL) {
- f->Print(", ");
+ f->AddString(", ");
value()->PrintTo(f);
}
}
-void AssertAssignableInstr::PrintOperandsTo(BufferFormatter* f) const {
+void AssertAssignableInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
dst_type()->PrintTo(f);
- f->Print(", '%s',", dst_name().ToCString());
- f->Print(" instantiator_type_args(");
+ f->Printf(", '%s',", dst_name().ToCString());
+ f->AddString(" instantiator_type_args(");
instantiator_type_arguments()->PrintTo(f);
- f->Print("), function_type_args(");
+ f->AddString("), function_type_args(");
function_type_arguments()->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void AssertSubtypeInstr::PrintOperandsTo(BufferFormatter* f) const {
+void AssertSubtypeInstr::PrintOperandsTo(BaseTextBuffer* f) const {
sub_type()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
super_type()->PrintTo(f);
- f->Print(", '%s', ", dst_name().ToCString());
- f->Print(" instantiator_type_args(");
+ f->Printf(", '%s', ", dst_name().ToCString());
+ f->AddString(" instantiator_type_args(");
instantiator_type_arguments()->PrintTo(f);
- f->Print("), function_type_args(");
+ f->AddString("), function_type_args(");
function_type_arguments()->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void AssertBooleanInstr::PrintOperandsTo(BufferFormatter* f) const {
+void AssertBooleanInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
}
-void ClosureCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print(" function=");
+void ClosureCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->AddString(" function=");
InputAt(InputCount() - 1)->PrintTo(f);
- f->Print("<%" Pd ">", type_args_len());
+ f->Printf("<%" Pd ">", type_args_len());
for (intptr_t i = 0; i < ArgumentCount(); ++i) {
- f->Print(", ");
+ f->AddString(", ");
ArgumentValueAt(i)->PrintTo(f);
}
if (entry_kind() == Code::EntryKind::kUnchecked) {
- f->Print(" using unchecked entrypoint");
+ f->AddString(" using unchecked entrypoint");
}
}
-void InstanceCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print(" %s<%" Pd ">", function_name().ToCString(), type_args_len());
+void InstanceCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf(" %s<%" Pd ">", function_name().ToCString(), type_args_len());
for (intptr_t i = 0; i < ArgumentCount(); ++i) {
- f->Print(", ");
+ f->AddString(", ");
ArgumentValueAt(i)->PrintTo(f);
}
if (HasICData()) {
@@ -480,287 +481,287 @@
}
}
if (result_type() != nullptr) {
- f->Print(", result_type = %s", result_type()->ToCString());
+ f->Printf(", result_type = %s", result_type()->ToCString());
}
if (entry_kind() == Code::EntryKind::kUnchecked) {
- f->Print(" using unchecked entrypoint");
+ f->AddString(" using unchecked entrypoint");
}
}
-void PolymorphicInstanceCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print(" %s<%" Pd ">", function_name().ToCString(), type_args_len());
+void PolymorphicInstanceCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf(" %s<%" Pd ">", function_name().ToCString(), type_args_len());
for (intptr_t i = 0; i < ArgumentCount(); ++i) {
- f->Print(", ");
+ f->AddString(", ");
ArgumentValueAt(i)->PrintTo(f);
}
PrintTargetsHelper(f, targets_, FlowGraphPrinter::kPrintAll);
if (complete()) {
- f->Print(" COMPLETE");
+ f->AddString(" COMPLETE");
}
if (entry_kind() == Code::EntryKind::kUnchecked) {
- f->Print(" using unchecked entrypoint");
+ f->AddString(" using unchecked entrypoint");
}
}
-void DispatchTableCallInstr::PrintOperandsTo(BufferFormatter* f) const {
+void DispatchTableCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
const String& name =
String::Handle(interface_target().QualifiedUserVisibleName());
- f->Print(" cid=");
+ f->AddString(" cid=");
class_id()->PrintTo(f);
- f->Print(" %s<%" Pd ">", name.ToCString(), type_args_len());
+ f->Printf(" %s<%" Pd ">", name.ToCString(), type_args_len());
for (intptr_t i = 0; i < ArgumentCount(); ++i) {
- f->Print(", ");
+ f->AddString(", ");
ArgumentValueAt(i)->PrintTo(f);
}
}
-void StrictCompareInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", Token::Str(kind()));
+void StrictCompareInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", Token::Str(kind()));
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
if (needs_number_check()) {
- f->Print(", with number check");
+ f->Printf(", with number check");
}
}
-void TestCidsInstr::PrintOperandsTo(BufferFormatter* f) const {
+void TestCidsInstr::PrintOperandsTo(BaseTextBuffer* f) const {
left()->PrintTo(f);
- f->Print(" %s [", Token::Str(kind()));
+ f->Printf(" %s [", Token::Str(kind()));
intptr_t length = cid_results().length();
for (intptr_t i = 0; i < length; i += 2) {
- f->Print("0x%" Px ":%s ", cid_results()[i],
- cid_results()[i + 1] == 0 ? "false" : "true");
+ f->Printf("0x%" Px ":%s ", cid_results()[i],
+ cid_results()[i + 1] == 0 ? "false" : "true");
}
- f->Print("] ");
+ f->AddString("] ");
if (CanDeoptimize()) {
ASSERT(deopt_id() != DeoptId::kNone);
- f->Print("else deoptimize ");
+ f->AddString("else deoptimize ");
} else {
ASSERT(deopt_id() == DeoptId::kNone);
- f->Print("else %s ", cid_results()[length - 1] != 0 ? "false" : "true");
+ f->Printf("else %s ", cid_results()[length - 1] != 0 ? "false" : "true");
}
}
-void EqualityCompareInstr::PrintOperandsTo(BufferFormatter* f) const {
+void EqualityCompareInstr::PrintOperandsTo(BaseTextBuffer* f) const {
left()->PrintTo(f);
- f->Print(" %s ", Token::Str(kind()));
+ f->Printf(" %s ", Token::Str(kind()));
right()->PrintTo(f);
}
-void StaticCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print(" %s<%" Pd "> ", String::Handle(function().name()).ToCString(),
- type_args_len());
+void StaticCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf(" %s<%" Pd "> ", String::Handle(function().name()).ToCString(),
+ type_args_len());
for (intptr_t i = 0; i < ArgumentCount(); ++i) {
- if (i > 0) f->Print(", ");
+ if (i > 0) f->AddString(", ");
ArgumentValueAt(i)->PrintTo(f);
}
if (entry_kind() == Code::EntryKind::kUnchecked) {
- f->Print(", using unchecked entrypoint");
+ f->AddString(", using unchecked entrypoint");
}
if (function().recognized_kind() != MethodRecognizer::kUnknown) {
- f->Print(", recognized_kind = %s",
- MethodRecognizer::KindToCString(function().recognized_kind()));
+ f->Printf(", recognized_kind = %s",
+ MethodRecognizer::KindToCString(function().recognized_kind()));
}
if (result_type() != nullptr) {
- f->Print(", result_type = %s", result_type()->ToCString());
+ f->Printf(", result_type = %s", result_type()->ToCString());
}
}
-void LoadLocalInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s @%d", local().name().ToCString(), local().index().value());
+void LoadLocalInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s @%d", local().name().ToCString(), local().index().value());
}
-void StoreLocalInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s @%d, ", local().name().ToCString(), local().index().value());
+void StoreLocalInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s @%d, ", local().name().ToCString(), local().index().value());
value()->PrintTo(f);
}
-void NativeCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", native_name().ToCString());
+void NativeCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", native_name().ToCString());
}
-void GuardFieldInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s %s, ", String::Handle(field().name()).ToCString(),
- field().GuardedPropertiesAsCString());
+void GuardFieldInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s %s, ", String::Handle(field().name()).ToCString(),
+ field().GuardedPropertiesAsCString());
value()->PrintTo(f);
}
-void StoreInstanceFieldInstr::PrintOperandsTo(BufferFormatter* f) const {
+void StoreInstanceFieldInstr::PrintOperandsTo(BaseTextBuffer* f) const {
instance()->PrintTo(f);
- f->Print(" . %s = ", slot().Name());
+ f->Printf(" . %s = ", slot().Name());
value()->PrintTo(f);
// Here, we just print the value of the enum field. We would prefer to get
// the final decision on whether a store barrier will be emitted by calling
// ShouldEmitStoreBarrier(), but that can change parts of the flow graph.
if (emit_store_barrier_ == kNoStoreBarrier) {
- f->Print(", NoStoreBarrier");
+ f->AddString(", NoStoreBarrier");
}
}
-void IfThenElseInstr::PrintOperandsTo(BufferFormatter* f) const {
+void IfThenElseInstr::PrintOperandsTo(BaseTextBuffer* f) const {
comparison()->PrintOperandsTo(f);
- f->Print(" ? %" Pd " : %" Pd, if_true_, if_false_);
+ f->Printf(" ? %" Pd " : %" Pd, if_true_, if_false_);
}
-void LoadStaticFieldInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", String::Handle(field().name()).ToCString());
+void LoadStaticFieldInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", String::Handle(field().name()).ToCString());
if (calls_initializer()) {
- f->Print(", CallsInitializer");
+ f->AddString(", CallsInitializer");
}
}
-void StoreStaticFieldInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", String::Handle(field().name()).ToCString());
+void StoreStaticFieldInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", String::Handle(field().name()).ToCString());
value()->PrintTo(f);
}
-void InstanceOfInstr::PrintOperandsTo(BufferFormatter* f) const {
+void InstanceOfInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
- f->Print(" IS %s,", String::Handle(type().Name()).ToCString());
- f->Print(" instantiator_type_args(");
+ f->Printf(" IS %s,", String::Handle(type().Name()).ToCString());
+ f->AddString(" instantiator_type_args(");
instantiator_type_arguments()->PrintTo(f);
- f->Print("), function_type_args(");
+ f->AddString("), function_type_args(");
function_type_arguments()->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void RelationalOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", Token::Str(kind()));
+void RelationalOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", Token::Str(kind()));
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
}
-void AllocateObjectInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", String::Handle(cls().ScrubbedName()).ToCString());
+void AllocateObjectInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", String::Handle(cls().ScrubbedName()).ToCString());
for (intptr_t i = 0; i < InputCount(); ++i) {
- f->Print(", ");
+ f->AddString(", ");
InputAt(i)->PrintTo(f);
}
if (Identity().IsNotAliased()) {
- f->Print(" <not-aliased>");
+ f->AddString(" <not-aliased>");
}
}
-void MaterializeObjectInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", String::Handle(cls_.ScrubbedName()).ToCString());
+void MaterializeObjectInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", String::Handle(cls_.ScrubbedName()).ToCString());
for (intptr_t i = 0; i < InputCount(); i++) {
- f->Print(", ");
- f->Print("%s: ", slots_[i]->Name());
+ f->AddString(", ");
+ f->Printf("%s: ", slots_[i]->Name());
InputAt(i)->PrintTo(f);
}
}
-void LoadFieldInstr::PrintOperandsTo(BufferFormatter* f) const {
+void LoadFieldInstr::PrintOperandsTo(BaseTextBuffer* f) const {
instance()->PrintTo(f);
- f->Print(" . %s%s", slot().Name(), slot().is_immutable() ? " {final}" : "");
+ f->Printf(" . %s%s", slot().Name(), slot().is_immutable() ? " {final}" : "");
if (calls_initializer()) {
- f->Print(", CallsInitializer");
+ f->AddString(", CallsInitializer");
}
}
-void LoadUntaggedInstr::PrintOperandsTo(BufferFormatter* f) const {
+void LoadUntaggedInstr::PrintOperandsTo(BaseTextBuffer* f) const {
object()->PrintTo(f);
- f->Print(", %" Pd, offset());
+ f->Printf(", %" Pd, offset());
}
-void InstantiateTypeInstr::PrintOperandsTo(BufferFormatter* f) const {
+void InstantiateTypeInstr::PrintOperandsTo(BaseTextBuffer* f) const {
const String& type_name = String::Handle(type().Name());
- f->Print("%s,", type_name.ToCString());
- f->Print(" instantiator_type_args(");
+ f->Printf("%s,", type_name.ToCString());
+ f->AddString(" instantiator_type_args(");
instantiator_type_arguments()->PrintTo(f);
- f->Print("), function_type_args(");
+ f->AddString("), function_type_args(");
function_type_arguments()->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void InstantiateTypeArgumentsInstr::PrintOperandsTo(BufferFormatter* f) const {
+void InstantiateTypeArgumentsInstr::PrintOperandsTo(BaseTextBuffer* f) const {
const String& type_args = String::Handle(type_arguments().Name());
- f->Print("%s,", type_args.ToCString());
- f->Print(" instantiator_type_args(");
+ f->Printf("%s,", type_args.ToCString());
+ f->AddString(" instantiator_type_args(");
instantiator_type_arguments()->PrintTo(f);
- f->Print("), function_type_args(");
+ f->AddString("), function_type_args(");
function_type_arguments()->PrintTo(f);
- f->Print("), instantiator_class(%s)", instantiator_class().ToCString());
+ f->Printf("), instantiator_class(%s)", instantiator_class().ToCString());
}
-void AllocateContextInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%" Pd "", num_context_variables());
+void AllocateContextInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%" Pd "", num_context_variables());
}
void AllocateUninitializedContextInstr::PrintOperandsTo(
- BufferFormatter* f) const {
- f->Print("%" Pd "", num_context_variables());
+ BaseTextBuffer* f) const {
+ f->Printf("%" Pd "", num_context_variables());
if (Identity().IsNotAliased()) {
- f->Print(" <not-aliased>");
+ f->AddString(" <not-aliased>");
}
}
-void MathUnaryInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("'%s', ", MathUnaryInstr::KindToCString(kind()));
+void MathUnaryInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("'%s', ", MathUnaryInstr::KindToCString(kind()));
value()->PrintTo(f);
}
-void TruncDivModInstr::PrintOperandsTo(BufferFormatter* f) const {
+void TruncDivModInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Definition::PrintOperandsTo(f);
}
-void ExtractNthOutputInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("Extract %" Pd " from ", index());
+void ExtractNthOutputInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("Extract %" Pd " from ", index());
Definition::PrintOperandsTo(f);
}
-void UnaryIntegerOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", Token::Str(op_kind()));
+void UnaryIntegerOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", Token::Str(op_kind()));
value()->PrintTo(f);
}
-void CheckedSmiOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", Token::Str(op_kind()));
- f->Print(", ");
+void CheckedSmiOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", Token::Str(op_kind()));
+ f->AddString(", ");
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
}
-void CheckedSmiComparisonInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", Token::Str(kind()));
- f->Print(", ");
+void CheckedSmiComparisonInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", Token::Str(kind()));
+ f->AddString(", ");
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
}
-void BinaryIntegerOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", Token::Str(op_kind()));
+void BinaryIntegerOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", Token::Str(op_kind()));
if (is_truncating()) {
- f->Print(" [tr]");
+ f->AddString(" [tr]");
} else if (!can_overflow()) {
- f->Print(" [-o]");
+ f->AddString(" [-o]");
}
- f->Print(", ");
+ f->AddString(", ");
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
}
-void BinaryDoubleOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", Token::Str(op_kind()));
+void BinaryDoubleOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", Token::Str(op_kind()));
left()->PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
right()->PrintTo(f);
}
-void DoubleTestOpInstr::PrintOperandsTo(BufferFormatter* f) const {
+void DoubleTestOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
switch (op_kind()) {
case MethodRecognizer::kDouble_getIsNaN:
- f->Print("IsNaN ");
+ f->AddString("IsNaN ");
break;
case MethodRecognizer::kDouble_getIsInfinite:
- f->Print("IsInfinite ");
+ f->AddString("IsInfinite ");
break;
default:
UNREACHABLE();
@@ -774,131 +775,131 @@
#undef CASE
};
-void SimdOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", simd_op_kind_string[kind()]);
+void SimdOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", simd_op_kind_string[kind()]);
if (HasMask()) {
- f->Print(", mask = %" Pd "", mask());
+ f->Printf(", mask = %" Pd "", mask());
}
for (intptr_t i = 0; i < InputCount(); i++) {
- f->Print(", ");
+ f->AddString(", ");
InputAt(i)->PrintTo(f);
}
}
-void UnaryDoubleOpInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", Token::Str(op_kind()));
+void UnaryDoubleOpInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", Token::Str(op_kind()));
value()->PrintTo(f);
}
-void LoadClassIdInstr::PrintOperandsTo(BufferFormatter* f) const {
+void LoadClassIdInstr::PrintOperandsTo(BaseTextBuffer* f) const {
if (!input_can_be_smi_) {
- f->Print("<non-smi> ");
+ f->AddString("<non-smi> ");
}
object()->PrintTo(f);
}
-void CheckClassIdInstr::PrintOperandsTo(BufferFormatter* f) const {
+void CheckClassIdInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
const Class& cls =
Class::Handle(Isolate::Current()->class_table()->At(cids().cid_start));
const String& name = String::Handle(cls.ScrubbedName());
if (cids().IsSingleCid()) {
- f->Print(", %s", name.ToCString());
+ f->Printf(", %s", name.ToCString());
} else {
const Class& cls2 =
Class::Handle(Isolate::Current()->class_table()->At(cids().cid_end));
const String& name2 = String::Handle(cls2.ScrubbedName());
- f->Print(", cid %" Pd "-%" Pd " %s-%s", cids().cid_start, cids().cid_end,
- name.ToCString(), name2.ToCString());
+ f->Printf(", cid %" Pd "-%" Pd " %s-%s", cids().cid_start, cids().cid_end,
+ name.ToCString(), name2.ToCString());
}
}
-void CheckClassInstr::PrintOperandsTo(BufferFormatter* f) const {
+void CheckClassInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
PrintCidsHelper(f, cids_, FlowGraphPrinter::kPrintAll);
if (IsNullCheck()) {
- f->Print(" nullcheck");
+ f->AddString(" nullcheck");
}
}
-void CheckConditionInstr::PrintOperandsTo(BufferFormatter* f) const {
+void CheckConditionInstr::PrintOperandsTo(BaseTextBuffer* f) const {
comparison()->PrintOperandsTo(f);
}
-void InvokeMathCFunctionInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s, ", MethodRecognizer::KindToCString(recognized_kind_));
+void InvokeMathCFunctionInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s, ", MethodRecognizer::KindToCString(recognized_kind_));
Definition::PrintOperandsTo(f);
}
void BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(
- BufferFormatter* f) const {
+ BaseTextBuffer* f) const {
const GrowableArray<Definition*>& defns = initial_definitions_;
if (defns.length() > 0) {
- f->Print(" {");
+ f->AddString(" {");
for (intptr_t i = 0; i < defns.length(); ++i) {
Definition* def = defns[i];
- f->Print("\n ");
+ f->AddString("\n ");
def->PrintTo(f);
}
- f->Print("\n}");
+ f->AddString("\n}");
}
}
-void GraphEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[graph]:%" Pd, block_id(), GetDeoptId());
+void GraphEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[graph]:%" Pd, block_id(), GetDeoptId());
BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(f);
}
-void JoinEntryInstr::PrintTo(BufferFormatter* f) const {
+void JoinEntryInstr::PrintTo(BaseTextBuffer* f) const {
if (try_index() != kInvalidTryIndex) {
- f->Print("B%" Pd "[join try_idx %" Pd "]:%" Pd " pred(", block_id(),
- try_index(), GetDeoptId());
+ f->Printf("B%" Pd "[join try_idx %" Pd "]:%" Pd " pred(", block_id(),
+ try_index(), GetDeoptId());
} else {
- f->Print("B%" Pd "[join]:%" Pd " pred(", block_id(), GetDeoptId());
+ f->Printf("B%" Pd "[join]:%" Pd " pred(", block_id(), GetDeoptId());
}
for (intptr_t i = 0; i < predecessors_.length(); ++i) {
- if (i > 0) f->Print(", ");
- f->Print("B%" Pd, predecessors_[i]->block_id());
+ if (i > 0) f->AddString(", ");
+ f->Printf("B%" Pd, predecessors_[i]->block_id());
}
- f->Print(")");
+ f->AddString(")");
if (phis_ != NULL) {
- f->Print(" {");
+ f->AddString(" {");
for (intptr_t i = 0; i < phis_->length(); ++i) {
if ((*phis_)[i] == NULL) continue;
- f->Print("\n ");
+ f->AddString("\n ");
(*phis_)[i]->PrintTo(f);
}
- f->Print("\n}");
+ f->AddString("\n}");
}
if (HasParallelMove()) {
- f->Print(" ");
+ f->AddString(" ");
parallel_move()->PrintTo(f);
}
}
-void IndirectEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[join indirect", block_id());
+void IndirectEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[join indirect", block_id());
if (try_index() != kInvalidTryIndex) {
- f->Print(" try_idx %" Pd, try_index());
+ f->Printf(" try_idx %" Pd, try_index());
}
- f->Print("]:%" Pd " pred(", GetDeoptId());
+ f->Printf("]:%" Pd " pred(", GetDeoptId());
for (intptr_t i = 0; i < predecessors_.length(); ++i) {
- if (i > 0) f->Print(", ");
- f->Print("B%" Pd, predecessors_[i]->block_id());
+ if (i > 0) f->AddString(", ");
+ f->Printf("B%" Pd, predecessors_[i]->block_id());
}
- f->Print(")");
+ f->AddString(")");
if (phis_ != NULL) {
- f->Print(" {");
+ f->AddString(" {");
for (intptr_t i = 0; i < phis_->length(); ++i) {
if ((*phis_)[i] == NULL) continue;
- f->Print("\n ");
+ f->AddString("\n ");
(*phis_)[i]->PrintTo(f);
}
- f->Print("\n}");
+ f->AddString("\n}");
}
if (HasParallelMove()) {
- f->Print(" ");
+ f->AddString(" ");
parallel_move()->PrintTo(f);
}
}
@@ -935,62 +936,58 @@
return "?";
}
-void PhiInstr::PrintTo(BufferFormatter* f) const {
+void PhiInstr::PrintTo(BaseTextBuffer* f) const {
if (HasPairRepresentation()) {
- f->Print("(v%" Pd ", v%" Pd ") <- phi(", ssa_temp_index(),
- ssa_temp_index() + 1);
+ f->Printf("(v%" Pd ", v%" Pd ") <- phi(", ssa_temp_index(),
+ ssa_temp_index() + 1);
} else {
- f->Print("v%" Pd " <- phi(", ssa_temp_index());
+ f->Printf("v%" Pd " <- phi(", ssa_temp_index());
}
for (intptr_t i = 0; i < inputs_.length(); ++i) {
if (inputs_[i] != NULL) inputs_[i]->PrintTo(f);
- if (i < inputs_.length() - 1) f->Print(", ");
+ if (i < inputs_.length() - 1) f->AddString(", ");
}
- f->Print(")");
- if (is_alive()) {
- f->Print(" alive");
- } else {
- f->Print(" dead");
- }
+ f->AddString(")");
+ f->AddString(is_alive() ? " alive" : " dead");
if (range_ != NULL) {
- f->Print(" ");
+ f->AddString(" ");
range_->PrintTo(f);
}
if (representation() != kNoRepresentation && representation() != kTagged) {
- f->Print(" %s", RepresentationToCString(representation()));
+ f->Printf(" %s", RepresentationToCString(representation()));
}
if (HasType()) {
- f->Print(" %s", TypeAsCString());
+ f->Printf(" %s", TypeAsCString());
}
}
-void UnboxIntegerInstr::PrintOperandsTo(BufferFormatter* f) const {
+void UnboxIntegerInstr::PrintOperandsTo(BaseTextBuffer* f) const {
if (is_truncating()) {
- f->Print("[tr], ");
+ f->AddString("[tr], ");
}
Definition::PrintOperandsTo(f);
}
-void IntConverterInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s->%s%s, ", RepresentationToCString(from()),
- RepresentationToCString(to()), is_truncating() ? "[tr]" : "");
+void IntConverterInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s->%s%s, ", RepresentationToCString(from()),
+ RepresentationToCString(to()), is_truncating() ? "[tr]" : "");
Definition::PrintOperandsTo(f);
}
-void BitCastInstr::PrintOperandsTo(BufferFormatter* f) const {
+void BitCastInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Definition::PrintOperandsTo(f);
- f->Print(" (%s -> %s)", RepresentationToCString(from()),
- RepresentationToCString(to()));
+ f->Printf(" (%s -> %s)", RepresentationToCString(from()),
+ RepresentationToCString(to()));
}
-void ParameterInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%" Pd, index());
+void ParameterInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%" Pd, index());
}
-void SpecialParameterInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s", KindToCString(kind()));
+void SpecialParameterInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s", KindToCString(kind()));
}
const char* SpecialParameterInstr::ToCString() const {
@@ -1000,125 +997,125 @@
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
-void CheckStackOverflowInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("stack=%" Pd ", loop=%" Pd, stack_depth(), loop_depth());
+void CheckStackOverflowInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("stack=%" Pd ", loop=%" Pd, stack_depth(), loop_depth());
}
-void TargetEntryInstr::PrintTo(BufferFormatter* f) const {
+void TargetEntryInstr::PrintTo(BaseTextBuffer* f) const {
if (try_index() != kInvalidTryIndex) {
- f->Print("B%" Pd "[target try_idx %" Pd "]:%" Pd, block_id(), try_index(),
- GetDeoptId());
+ f->Printf("B%" Pd "[target try_idx %" Pd "]:%" Pd, block_id(), try_index(),
+ GetDeoptId());
} else {
- f->Print("B%" Pd "[target]:%" Pd, block_id(), GetDeoptId());
+ f->Printf("B%" Pd "[target]:%" Pd, block_id(), GetDeoptId());
}
if (HasParallelMove()) {
- f->Print(" ");
+ f->AddString(" ");
parallel_move()->PrintTo(f);
}
}
-void OsrEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[osr entry]:%" Pd " stack_depth=%" Pd, block_id(),
- GetDeoptId(), stack_depth());
+void OsrEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[osr entry]:%" Pd " stack_depth=%" Pd, block_id(),
+ GetDeoptId(), stack_depth());
if (HasParallelMove()) {
- f->Print("\n");
+ f->AddString("\n");
parallel_move()->PrintTo(f);
}
BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(f);
}
-void FunctionEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[function entry]:%" Pd, block_id(), GetDeoptId());
+void FunctionEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[function entry]:%" Pd, block_id(), GetDeoptId());
if (HasParallelMove()) {
- f->Print("\n");
+ f->AddString("\n");
parallel_move()->PrintTo(f);
}
BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(f);
}
-void NativeEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[native function entry]:%" Pd, block_id(), GetDeoptId());
+void NativeEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[native function entry]:%" Pd, block_id(), GetDeoptId());
if (HasParallelMove()) {
- f->Print("\n");
+ f->AddString("\n");
parallel_move()->PrintTo(f);
}
BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(f);
}
-void ReturnInstr::PrintOperandsTo(BufferFormatter* f) const {
+void ReturnInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Instruction::PrintOperandsTo(f);
if (yield_index() != PcDescriptorsLayout::kInvalidYieldIndex) {
- f->Print(", yield_index = %" Pd "", yield_index());
+ f->Printf(", yield_index = %" Pd "", yield_index());
}
}
-void FfiCallInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print(" pointer=");
+void FfiCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->AddString(" pointer=");
InputAt(TargetAddressIndex())->PrintTo(f);
for (intptr_t i = 0, n = InputCount(); i < n - 1; ++i) {
- f->Print(", ");
+ f->AddString(", ");
InputAt(i)->PrintTo(f);
- f->Print(" (@");
+ f->AddString(" (@");
marshaller_.Location(i).PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
}
-void EnterHandleScopeInstr::PrintOperandsTo(BufferFormatter* f) const {
+void EnterHandleScopeInstr::PrintOperandsTo(BaseTextBuffer* f) const {
if (kind_ == Kind::kEnterHandleScope) {
- f->Print("<enter handle scope>");
+ f->AddString("<enter handle scope>");
} else {
- f->Print("<get top api scope>");
+ f->AddString("<get top api scope>");
}
}
-void NativeReturnInstr::PrintOperandsTo(BufferFormatter* f) const {
+void NativeReturnInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
- f->Print(" (@");
+ f->AddString(" (@");
marshaller_.Location(compiler::ffi::kResultIndex).PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void NativeParameterInstr::PrintOperandsTo(BufferFormatter* f) const {
+void NativeParameterInstr::PrintOperandsTo(BaseTextBuffer* f) const {
// Where the calling convention puts it.
marshaller_.Location(index_).PrintTo(f);
- f->Print(" at ");
+ f->AddString(" at ");
// Where the arguments are when pushed on the stack.
marshaller_.NativeLocationOfNativeParameter(index_).PrintTo(f);
}
-void CatchBlockEntryInstr::PrintTo(BufferFormatter* f) const {
- f->Print("B%" Pd "[target catch try_idx %" Pd " catch_try_idx %" Pd "]",
- block_id(), try_index(), catch_try_index());
+void CatchBlockEntryInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("B%" Pd "[target catch try_idx %" Pd " catch_try_idx %" Pd "]",
+ block_id(), try_index(), catch_try_index());
if (HasParallelMove()) {
- f->Print("\n");
+ f->AddString("\n");
parallel_move()->PrintTo(f);
}
BlockEntryWithInitialDefs::PrintInitialDefinitionsTo(f);
}
-void LoadIndexedUnsafeInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s[", RegisterNames::RegisterName(base_reg()));
+void LoadIndexedUnsafeInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s[", RegisterNames::RegisterName(base_reg()));
index()->PrintTo(f);
- f->Print(" + %" Pd "]", offset());
+ f->Printf(" + %" Pd "]", offset());
}
-void StoreIndexedUnsafeInstr::PrintOperandsTo(BufferFormatter* f) const {
- f->Print("%s[", RegisterNames::RegisterName(base_reg()));
+void StoreIndexedUnsafeInstr::PrintOperandsTo(BaseTextBuffer* f) const {
+ f->Printf("%s[", RegisterNames::RegisterName(base_reg()));
index()->PrintTo(f);
- f->Print(" + %" Pd "], ", offset());
+ f->Printf(" + %" Pd "], ", offset());
value()->PrintTo(f);
}
-void StoreIndexedInstr::PrintOperandsTo(BufferFormatter* f) const {
+void StoreIndexedInstr::PrintOperandsTo(BaseTextBuffer* f) const {
Instruction::PrintOperandsTo(f);
if (!ShouldEmitStoreBarrier()) {
- f->Print(", NoStoreBarrier");
+ f->AddString(", NoStoreBarrier");
}
}
-void TailCallInstr::PrintOperandsTo(BufferFormatter* f) const {
+void TailCallInstr::PrintOperandsTo(BaseTextBuffer* f) const {
const char* name = "<unknown code>";
if (code_.IsStubCode()) {
name = StubCode::NameOfStub(code_.EntryPoint());
@@ -1129,78 +1126,78 @@
.ToFullyQualifiedCString();
}
}
- f->Print("%s(", name);
+ f->Printf("%s(", name);
InputAt(0)->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void PushArgumentInstr::PrintOperandsTo(BufferFormatter* f) const {
+void PushArgumentInstr::PrintOperandsTo(BaseTextBuffer* f) const {
value()->PrintTo(f);
}
-void GotoInstr::PrintTo(BufferFormatter* f) const {
+void GotoInstr::PrintTo(BaseTextBuffer* f) const {
if (HasParallelMove()) {
parallel_move()->PrintTo(f);
- f->Print(" ");
+ f->AddString(" ");
}
if (GetDeoptId() != DeoptId::kNone) {
- f->Print("goto:%" Pd " B%" Pd "", GetDeoptId(), successor()->block_id());
+ f->Printf("goto:%" Pd " B%" Pd "", GetDeoptId(), successor()->block_id());
} else {
- f->Print("goto: B%" Pd "", successor()->block_id());
+ f->Printf("goto: B%" Pd "", successor()->block_id());
}
}
-void IndirectGotoInstr::PrintTo(BufferFormatter* f) const {
+void IndirectGotoInstr::PrintTo(BaseTextBuffer* f) const {
if (GetDeoptId() != DeoptId::kNone) {
- f->Print("igoto:%" Pd "(", GetDeoptId());
+ f->Printf("igoto:%" Pd "(", GetDeoptId());
} else {
- f->Print("igoto:(");
+ f->AddString("igoto:(");
}
InputAt(0)->PrintTo(f);
- f->Print(")");
+ f->AddString(")");
}
-void BranchInstr::PrintTo(BufferFormatter* f) const {
- f->Print("%s ", DebugName());
- f->Print("if ");
+void BranchInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("%s ", DebugName());
+ f->AddString("if ");
comparison()->PrintTo(f);
- f->Print(" goto (%" Pd ", %" Pd ")", true_successor()->block_id(),
- false_successor()->block_id());
+ f->Printf(" goto (%" Pd ", %" Pd ")", true_successor()->block_id(),
+ false_successor()->block_id());
}
-void ParallelMoveInstr::PrintTo(BufferFormatter* f) const {
- f->Print("%s ", DebugName());
+void ParallelMoveInstr::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("%s ", DebugName());
for (intptr_t i = 0; i < moves_.length(); i++) {
- if (i != 0) f->Print(", ");
+ if (i != 0) f->AddString(", ");
moves_[i]->dest().PrintTo(f);
- f->Print(" <- ");
+ f->AddString(" <- ");
moves_[i]->src().PrintTo(f);
}
}
-void Utf8ScanInstr::PrintTo(BufferFormatter* f) const {
+void Utf8ScanInstr::PrintTo(BaseTextBuffer* f) const {
Definition::PrintTo(f);
- f->Print(" [%s]", scan_flags_field_.Name());
+ f->Printf(" [%s]", scan_flags_field_.Name());
}
-void Environment::PrintTo(BufferFormatter* f) const {
- f->Print(" env={ ");
+void Environment::PrintTo(BaseTextBuffer* f) const {
+ f->AddString(" env={ ");
int arg_count = 0;
for (intptr_t i = 0; i < values_.length(); ++i) {
- if (i > 0) f->Print(", ");
+ if (i > 0) f->AddString(", ");
if (values_[i]->definition()->IsPushArgument()) {
- f->Print("a%d", arg_count++);
+ f->Printf("a%d", arg_count++);
} else {
values_[i]->PrintTo(f);
}
if ((locations_ != NULL) && !locations_[i].IsInvalid()) {
- f->Print(" [");
+ f->AddString(" [");
locations_[i].PrintTo(f);
- f->Print("]");
+ f->AddString("]");
}
}
- f->Print(" }");
+ f->AddString(" }");
if (outer_ != NULL) outer_->PrintTo(f);
}
diff --git a/runtime/vm/compiler/backend/il_serializer.cc b/runtime/vm/compiler/backend/il_serializer.cc
index 309224d..5e6fc92 100644
--- a/runtime/vm/compiler/backend/il_serializer.cc
+++ b/runtime/vm/compiler/backend/il_serializer.cc
@@ -10,6 +10,7 @@
#include "vm/compiler/method_recognizer.h"
#include "vm/object_store.h"
#include "vm/os.h"
+#include "vm/zone_text_buffer.h"
namespace dart {
@@ -75,14 +76,9 @@
object_store_->set_llvm_constant_hash_table(llvm_constant_map_.Release());
}
-void FlowGraphSerializer::SerializeToBuffer(const FlowGraph* flow_graph,
- TextBuffer* buffer) {
- SerializeToBuffer(Thread::Current()->zone(), flow_graph, buffer);
-}
-
void FlowGraphSerializer::SerializeToBuffer(Zone* zone,
const FlowGraph* flow_graph,
- TextBuffer* buffer) {
+ BaseTextBuffer* buffer) {
ASSERT(buffer != nullptr);
auto const sexp = SerializeToSExp(zone, flow_graph);
if (FLAG_pretty_print_serialization) {
@@ -93,10 +89,6 @@
buffer->AddString("\n\n");
}
-SExpression* FlowGraphSerializer::SerializeToSExp(const FlowGraph* flow_graph) {
- return SerializeToSExp(Thread::Current()->zone(), flow_graph);
-}
-
SExpression* FlowGraphSerializer::SerializeToSExp(Zone* zone,
const FlowGraph* flow_graph) {
FlowGraphSerializer serializer(zone, flow_graph);
@@ -163,7 +155,7 @@
return new (zone()) SExpSymbol(OS::SCreate(zone(), "B%" Pd "", block_id));
}
-void FlowGraphSerializer::SerializeCanonicalName(TextBuffer* b,
+void FlowGraphSerializer::SerializeCanonicalName(BaseTextBuffer* b,
const Object& obj) {
ASSERT(!obj.IsNull());
if (obj.IsFunction()) {
@@ -223,9 +215,9 @@
SExpression* FlowGraphSerializer::CanonicalNameToSExp(const Object& obj) {
ASSERT(!obj.IsNull());
- TextBuffer b(100);
+ ZoneTextBuffer b(zone_, 100);
SerializeCanonicalName(&b, obj);
- return new (zone()) SExpSymbol(OS::SCreate(zone(), "%s", b.buf()));
+ return new (zone()) SExpSymbol(b.buffer());
}
SExpSymbol* FlowGraphSerializer::BlockEntryKindToTag(BlockEntryKind k) {
diff --git a/runtime/vm/compiler/backend/il_serializer.h b/runtime/vm/compiler/backend/il_serializer.h
index 8a65fad3..c5d8d6f 100644
--- a/runtime/vm/compiler/backend/il_serializer.h
+++ b/runtime/vm/compiler/backend/il_serializer.h
@@ -50,12 +50,9 @@
SExpSymbol* BlockEntryKindToTag(BlockEntryKind k);
static bool BlockEntryKindHasInitialDefs(BlockEntryKind kind);
- static void SerializeToBuffer(const FlowGraph* flow_graph,
- TextBuffer* buffer);
static void SerializeToBuffer(Zone* zone,
const FlowGraph* flow_graph,
- TextBuffer* buffer);
- static SExpression* SerializeToSExp(const FlowGraph* flow_graph);
+ BaseTextBuffer* buffer);
static SExpression* SerializeToSExp(Zone* zone, const FlowGraph* flow_graph);
const FlowGraph* flow_graph() const { return flow_graph_; }
@@ -69,7 +66,7 @@
SExpression* UseToSExp(const Definition* definition);
// Helper method for creating canonical names.
- void SerializeCanonicalName(TextBuffer* b, const Object& obj);
+ void SerializeCanonicalName(BaseTextBuffer* b, const Object& obj);
// Methods for serializing Dart values. If the argument
// value is the null object, the null pointer is returned.
diff --git a/runtime/vm/compiler/backend/locations.cc b/runtime/vm/compiler/backend/locations.cc
index 8d7c759..2c40969 100644
--- a/runtime/vm/compiler/backend/locations.cc
+++ b/runtime/vm/compiler/backend/locations.cc
@@ -249,24 +249,24 @@
return "?";
}
-void Location::PrintTo(BufferFormatter* f) const {
+void Location::PrintTo(BaseTextBuffer* f) const {
if (!FLAG_support_il_printer) {
return;
}
if (kind() == kStackSlot) {
- f->Print("S%+" Pd "", stack_index());
+ f->Printf("S%+" Pd "", stack_index());
} else if (kind() == kDoubleStackSlot) {
- f->Print("DS%+" Pd "", stack_index());
+ f->Printf("DS%+" Pd "", stack_index());
} else if (kind() == kQuadStackSlot) {
- f->Print("QS%+" Pd "", stack_index());
+ f->Printf("QS%+" Pd "", stack_index());
} else if (IsPairLocation()) {
- f->Print("(");
+ f->AddString("(");
AsPairLocation()->At(0).PrintTo(f);
- f->Print(", ");
+ f->AddString(", ");
AsPairLocation()->At(1).PrintTo(f);
- f->Print(")");
+ f->AddString(")");
} else {
- f->Print("%s", Name());
+ f->Printf("%s", Name());
}
}
@@ -371,34 +371,34 @@
return loc;
}
-void LocationSummary::PrintTo(BufferFormatter* f) const {
+void LocationSummary::PrintTo(BaseTextBuffer* f) const {
if (!FLAG_support_il_printer) {
return;
}
if (input_count() > 0) {
- f->Print(" (");
+ f->AddString(" (");
for (intptr_t i = 0; i < input_count(); i++) {
- if (i != 0) f->Print(", ");
+ if (i != 0) f->AddString(", ");
in(i).PrintTo(f);
}
- f->Print(")");
+ f->AddString(")");
}
if (temp_count() > 0) {
- f->Print(" [");
+ f->AddString(" [");
for (intptr_t i = 0; i < temp_count(); i++) {
- if (i != 0) f->Print(", ");
+ if (i != 0) f->AddString(", ");
temp(i).PrintTo(f);
}
- f->Print("]");
+ f->AddString("]");
}
if (!out(0).IsInvalid()) {
- f->Print(" => ");
+ f->AddString(" => ");
out(0).PrintTo(f);
}
- if (always_calls()) f->Print(" C");
+ if (always_calls()) f->AddString(" C");
}
#if defined(DEBUG)
diff --git a/runtime/vm/compiler/backend/locations.h b/runtime/vm/compiler/backend/locations.h
index d685250..34edf4c 100644
--- a/runtime/vm/compiler/backend/locations.h
+++ b/runtime/vm/compiler/backend/locations.h
@@ -18,7 +18,7 @@
namespace dart {
-class BufferFormatter;
+class BaseTextBuffer;
class ConstantInstr;
class Definition;
class PairLocation;
@@ -351,7 +351,7 @@
intptr_t ToStackSlotOffset() const;
const char* Name() const;
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
void Print() const;
const char* ToCString() const;
@@ -723,7 +723,7 @@
return contains_call_ == kCallOnSharedSlowPath;
}
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
static LocationSummary* Make(Zone* zone,
intptr_t input_count,
diff --git a/runtime/vm/compiler/backend/loops.cc b/runtime/vm/compiler/backend/loops.cc
index 21a4a77..4ff2dc8 100644
--- a/runtime/vm/compiler/backend/loops.cc
+++ b/runtime/vm/compiler/backend/loops.cc
@@ -941,28 +941,32 @@
return false;
}
-const char* InductionVar::ToCString() const {
- char buffer[1024];
- BufferFormatter f(buffer, sizeof(buffer));
+void InductionVar::PrintTo(BaseTextBuffer* f) const {
switch (kind_) {
case kInvariant:
if (mult_ != 0) {
- f.Print("(%" Pd64 " + %" Pd64 " x %.4s)", offset_, mult_,
- def_->ToCString());
+ f->Printf("(%" Pd64 " + %" Pd64 " x %.4s)", offset_, mult_,
+ def_->ToCString());
} else {
- f.Print("%" Pd64, offset_);
+ f->Printf("%" Pd64, offset_);
}
break;
case kLinear:
- f.Print("LIN(%s + %s * i)", initial_->ToCString(), next_->ToCString());
+ f->Printf("LIN(%s + %s * i)", initial_->ToCString(), next_->ToCString());
break;
case kWrapAround:
- f.Print("WRAP(%s, %s)", initial_->ToCString(), next_->ToCString());
+ f->Printf("WRAP(%s, %s)", initial_->ToCString(), next_->ToCString());
break;
case kPeriodic:
- f.Print("PERIOD(%s, %s)", initial_->ToCString(), next_->ToCString());
+ f->Printf("PERIOD(%s, %s)", initial_->ToCString(), next_->ToCString());
break;
}
+}
+
+const char* InductionVar::ToCString() const {
+ char buffer[1024];
+ BufferFormatter f(buffer, sizeof(buffer));
+ PrintTo(&f);
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
@@ -1112,24 +1116,28 @@
return false;
}
-const char* LoopInfo::ToCString() const {
- char buffer[1024];
- BufferFormatter f(buffer, sizeof(buffer));
- f.Print("%*c", static_cast<int>(2 * NestingDepth()), ' ');
- f.Print("loop%" Pd " B%" Pd " ", id_, header_->block_id());
+void LoopInfo::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("%*c", static_cast<int>(2 * NestingDepth()), ' ');
+ f->Printf("loop%" Pd " B%" Pd " ", id_, header_->block_id());
intptr_t num_blocks = 0;
for (BitVector::Iterator it(blocks_); !it.Done(); it.Advance()) {
num_blocks++;
}
- f.Print("#blocks=%" Pd, num_blocks);
- if (outer_ != nullptr) f.Print(" outer=%" Pd, outer_->id_);
- if (inner_ != nullptr) f.Print(" inner=%" Pd, inner_->id_);
- if (next_ != nullptr) f.Print(" next=%" Pd, next_->id_);
- f.Print(" [");
+ f->Printf("#blocks=%" Pd, num_blocks);
+ if (outer_ != nullptr) f->Printf(" outer=%" Pd, outer_->id_);
+ if (inner_ != nullptr) f->Printf(" inner=%" Pd, inner_->id_);
+ if (next_ != nullptr) f->Printf(" next=%" Pd, next_->id_);
+ f->AddString(" [");
for (intptr_t i = 0, n = back_edges_.length(); i < n; i++) {
- f.Print(" B%" Pd, back_edges_[i]->block_id());
+ f->Printf(" B%" Pd, back_edges_[i]->block_id());
}
- f.Print(" ]");
+ f->AddString(" ]");
+}
+
+const char* LoopInfo::ToCString() const {
+ char buffer[1024];
+ BufferFormatter f(buffer, sizeof(buffer));
+ PrintTo(&f);
return Thread::Current()->zone()->MakeCopyOfString(buffer);
}
diff --git a/runtime/vm/compiler/backend/loops.h b/runtime/vm/compiler/backend/loops.h
index 704508b..9a70102 100644
--- a/runtime/vm/compiler/backend/loops.h
+++ b/runtime/vm/compiler/backend/loops.h
@@ -128,6 +128,7 @@
const GrowableArray<Bound>& bounds() { return bounds_; }
// For debugging.
+ void PrintTo(BaseTextBuffer* f) const;
const char* ToCString() const;
// Returns true if x is invariant.
@@ -258,6 +259,7 @@
LoopInfo* next() const { return next_; }
// For debugging.
+ void PrintTo(BaseTextBuffer* f) const;
const char* ToCString() const;
private:
diff --git a/runtime/vm/compiler/backend/loops_test.cc b/runtime/vm/compiler/backend/loops_test.cc
index 3898334..8f1201e 100644
--- a/runtime/vm/compiler/backend/loops_test.cc
+++ b/runtime/vm/compiler/backend/loops_test.cc
@@ -24,12 +24,12 @@
namespace dart {
// Helper method to construct an induction debug string for loop hierarchy.
-void TestString(BufferFormatter* f,
+void TestString(BaseTextBuffer* f,
LoopInfo* loop,
const GrowableArray<BlockEntryInstr*>& preorder) {
for (; loop != nullptr; loop = loop->next()) {
intptr_t depth = loop->NestingDepth();
- f->Print("%*c[%" Pd "\n", static_cast<int>(2 * depth), ' ', loop->id());
+ f->Printf("%*c[%" Pd "\n", static_cast<int>(2 * depth), ' ', loop->id());
for (BitVector::Iterator block_it(loop->blocks()); !block_it.Done();
block_it.Advance()) {
BlockEntryInstr* block = preorder[block_it.Current()];
@@ -38,12 +38,12 @@
InductionVar* induc = loop->LookupInduction(it.Current());
if (induc != nullptr) {
// Obtain the debug string for induction and bounds.
- f->Print("%*c%s", static_cast<int>(2 * depth), ' ',
- induc->ToCString());
+ f->Printf("%*c%s", static_cast<int>(2 * depth), ' ',
+ induc->ToCString());
for (auto bound : induc->bounds()) {
- f->Print(" %s", bound.limit_->ToCString());
+ f->Printf(" %s", bound.limit_->ToCString());
}
- f->Print("\n");
+ f->AddString("\n");
}
}
}
@@ -51,13 +51,13 @@
InductionVar* induc =
loop->LookupInduction(it.Current()->AsDefinition());
if (InductionVar::IsInduction(induc)) {
- f->Print("%*c%s\n", static_cast<int>(2 * depth), ' ',
- induc->ToCString());
+ f->Printf("%*c%s\n", static_cast<int>(2 * depth), ' ',
+ induc->ToCString());
}
}
}
TestString(f, loop->inner(), preorder);
- f->Print("%*c]\n", static_cast<int>(2 * depth), ' ');
+ f->Printf("%*c]\n", static_cast<int>(2 * depth), ' ');
}
}
diff --git a/runtime/vm/compiler/backend/range_analysis.cc b/runtime/vm/compiler/backend/range_analysis.cc
index a802eaa..281e3c9 100644
--- a/runtime/vm/compiler/backend/range_analysis.cc
+++ b/runtime/vm/compiler/backend/range_analysis.cc
@@ -1310,22 +1310,22 @@
}
#ifndef PRODUCT
- static void PrettyPrintIndexBoundRecursively(BufferFormatter* f,
+ static void PrettyPrintIndexBoundRecursively(BaseTextBuffer* f,
Definition* index_bound) {
BinarySmiOpInstr* binary_op = index_bound->AsBinarySmiOp();
if (binary_op != NULL) {
- f->Print("(");
+ f->AddString("(");
PrettyPrintIndexBoundRecursively(f, binary_op->left()->definition());
- f->Print(" %s ", Token::Str(binary_op->op_kind()));
+ f->Printf(" %s ", Token::Str(binary_op->op_kind()));
PrettyPrintIndexBoundRecursively(f, binary_op->right()->definition());
- f->Print(")");
+ f->AddString(")");
} else if (index_bound->IsConstant()) {
- f->Print("%" Pd "",
- Smi::Cast(index_bound->AsConstant()->value()).Value());
+ f->Printf("%" Pd "",
+ Smi::Cast(index_bound->AsConstant()->value()).Value());
} else {
- f->Print("v%" Pd "", index_bound->ssa_temp_index());
+ f->Printf("v%" Pd "", index_bound->ssa_temp_index());
}
- f->Print(" {%s}", Range::ToCString(index_bound->range()));
+ f->Printf(" {%s}", Range::ToCString(index_bound->range()));
}
static const char* IndexBoundToCString(Definition* index_bound) {
diff --git a/runtime/vm/compiler/backend/range_analysis.h b/runtime/vm/compiler/backend/range_analysis.h
index 0ed4936..0f8cc42 100644
--- a/runtime/vm/compiler/backend/range_analysis.h
+++ b/runtime/vm/compiler/backend/range_analysis.h
@@ -244,7 +244,7 @@
// IsSymbol() -> upper bound computed from definition + offset.
RangeBoundary UpperBound() const;
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
const char* ToCString() const;
SExpression* ToSExpression(FlowGraphSerializer* s);
@@ -345,7 +345,7 @@
RangeBoundary::MaxConstant(size));
}
- void PrintTo(BufferFormatter* f) const;
+ void PrintTo(BaseTextBuffer* f) const;
static const char* ToCString(const Range* range);
SExpression* ToSExpression(FlowGraphSerializer* s);
diff --git a/runtime/vm/compiler/backend/sexpression.cc b/runtime/vm/compiler/backend/sexpression.cc
index 12006b4..7307ef3 100644
--- a/runtime/vm/compiler/backend/sexpression.cc
+++ b/runtime/vm/compiler/backend/sexpression.cc
@@ -7,6 +7,7 @@
#include <ctype.h>
#include "platform/utils.h"
#include "vm/double_conversion.h"
+#include "vm/zone_text_buffer.h"
namespace dart {
@@ -18,13 +19,9 @@
}
const char* SExpression::ToCString(Zone* zone) const {
- TextBuffer buf(1 * KB);
+ ZoneTextBuffer buf(zone, 1 * KB);
SerializeToLine(&buf);
- auto const buf_len = buf.length();
- char* ret = zone->Alloc<char>(buf_len + 1);
- strncpy(ret, buf.buf(), buf_len);
- ret[buf_len] = '\0';
- return ret;
+ return buf.buffer();
}
bool SExpBool::Equals(SExpression* sexp) const {
@@ -36,7 +33,7 @@
return value() == val;
}
-void SExpBool::SerializeToLine(TextBuffer* buffer) const {
+void SExpBool::SerializeToLine(BaseTextBuffer* buffer) const {
buffer->AddString(value() ? SExpParser::kBoolTrueSymbol
: SExpParser::kBoolFalseSymbol);
}
@@ -50,7 +47,7 @@
return value() == val;
}
-void SExpDouble::SerializeToLine(TextBuffer* buffer) const {
+void SExpDouble::SerializeToLine(BaseTextBuffer* buffer) const {
// Use existing Dart serialization for Doubles.
const intptr_t kBufSize = 128;
char strbuf[kBufSize];
@@ -67,7 +64,7 @@
return value() == val;
}
-void SExpInteger::SerializeToLine(TextBuffer* buffer) const {
+void SExpInteger::SerializeToLine(BaseTextBuffer* buffer) const {
buffer->Printf("%" Pd64 "", value());
}
@@ -80,10 +77,12 @@
return strcmp(value(), str) == 0;
}
-void SExpString::SerializeToLine(TextBuffer* buffer) const {
- buffer->AddChar('"');
- buffer->AddEscapedString(value());
- buffer->AddChar('"');
+void SExpString::SerializeToLine(BaseTextBuffer* buffer) const {
+ TextBuffer buf(80);
+ buf.AddChar('"');
+ buf.AddEscapedString(value());
+ buf.AddChar('"');
+ buffer->AddString(buf.buffer());
}
bool SExpSymbol::Equals(SExpression* sexp) const {
@@ -95,7 +94,7 @@
return strcmp(value(), str) == 0;
}
-void SExpSymbol::SerializeToLine(TextBuffer* buffer) const {
+void SExpSymbol::SerializeToLine(BaseTextBuffer* buffer) const {
buffer->AddString(value());
}
@@ -128,9 +127,9 @@
const char* const SExpList::kExtraIndent = " ";
static intptr_t HandleLineBreaking(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
SExpression* element,
- TextBuffer* line_buffer,
+ BaseTextBuffer* line_buffer,
const char* sub_indent,
intptr_t width,
bool leading_space,
@@ -141,7 +140,7 @@
if ((leading_length + single_line_width) < remaining) {
if (leading_space) buffer->AddChar(' ');
- buffer->AddString(line_buffer->buf());
+ buffer->AddString(line_buffer->buffer());
line_buffer->Clear();
return remaining - (leading_length + single_line_width);
}
@@ -150,7 +149,7 @@
const intptr_t line_used = buffer->length() - old_length + 1;
remaining = width - line_used;
if ((single_line_width < remaining) || element->IsAtom()) {
- buffer->AddString(line_buffer->buf());
+ buffer->AddString(line_buffer->buffer());
line_buffer->Clear();
return remaining - single_line_width;
}
@@ -161,7 +160,7 @@
// Assumes that we are starting on a line after [indent] amount of space.
void SExpList::SerializeTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
intptr_t width) const {
TextBuffer single_line(width);
@@ -177,14 +176,14 @@
if (!extra_info_.IsEmpty()) {
SerializeExtraInfoToLine(&single_line);
if (single_line.length() < remaining - 1) {
- buffer->Printf(" %s", single_line.buf());
+ buffer->Printf(" %s", single_line.buffer());
} else {
const intptr_t old_length = buffer->length();
buffer->Printf("\n%s", sub_indent);
const intptr_t line_used = buffer->length() - old_length + 1;
remaining = width - line_used;
if (single_line.length() < remaining) {
- buffer->AddString(single_line.buf());
+ buffer->AddString(single_line.buffer());
} else {
SerializeExtraInfoTo(zone, buffer, sub_indent, width);
}
@@ -193,7 +192,7 @@
buffer->AddChar(')');
}
-void SExpList::SerializeToLine(TextBuffer* buffer) const {
+void SExpList::SerializeToLine(BaseTextBuffer* buffer) const {
buffer->AddChar('(');
for (intptr_t i = 0; i < contents_.length(); i++) {
if (i != 0) buffer->AddChar(' ');
@@ -207,7 +206,7 @@
}
void SExpList::SerializeExtraInfoTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
int width) const {
const char* sub_indent = OS::SCreate(zone, "%s%s", indent, kExtraIndent);
@@ -226,7 +225,7 @@
buffer->Printf("\n%s}", indent);
}
-void SExpList::SerializeExtraInfoToLine(TextBuffer* buffer) const {
+void SExpList::SerializeExtraInfoToLine(BaseTextBuffer* buffer) const {
buffer->AddString("{");
auto it = ExtraIterator();
while (auto kv = it.Next()) {
diff --git a/runtime/vm/compiler/backend/sexpression.h b/runtime/vm/compiler/backend/sexpression.h
index 40b79a3..6bdc36e 100644
--- a/runtime/vm/compiler/backend/sexpression.h
+++ b/runtime/vm/compiler/backend/sexpression.h
@@ -81,10 +81,10 @@
virtual const char* DebugName() const = 0;
virtual bool Equals(SExpression* sexp) const = 0;
virtual void SerializeTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
intptr_t width = 80) const = 0;
- virtual void SerializeToLine(TextBuffer* buffer) const = 0;
+ virtual void SerializeToLine(BaseTextBuffer* buffer) const = 0;
private:
// Starting character position of the s-expression in the original
@@ -100,7 +100,7 @@
virtual const SExpAtom* AsAtom() const { return this; }
// No atoms have sub-elements, so they always print to a single line.
virtual void SerializeTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
intptr_t width = 80) const {
SerializeToLine(buffer);
@@ -124,7 +124,7 @@
value_type value() const { return val_; } \
virtual bool Equals(SExpression* sexp) const; \
bool Equals(value_type val) const; \
- virtual void SerializeToLine(TextBuffer* buffer) const; \
+ virtual void SerializeToLine(BaseTextBuffer* buffer) const; \
DEFINE_S_EXPRESSION_TYPE_CHECK(name) \
private: \
value_type const val_; \
@@ -168,20 +168,20 @@
DEFINE_S_EXPRESSION_TYPE_CHECK(List)
virtual bool Equals(SExpression* sexp) const;
virtual void SerializeTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
intptr_t width = 80) const;
- virtual void SerializeToLine(TextBuffer* buffer) const;
+ virtual void SerializeToLine(BaseTextBuffer* buffer) const;
private:
static const char* const kElemIndent;
static const char* const kExtraIndent;
void SerializeExtraInfoTo(Zone* zone,
- TextBuffer* buffer,
+ BaseTextBuffer* buffer,
const char* indent,
int width) const;
- void SerializeExtraInfoToLine(TextBuffer* buffer) const;
+ void SerializeExtraInfoToLine(BaseTextBuffer* buffer) const;
ZoneGrowableArray<SExpression*> contents_;
ExtraInfoHashMap extra_info_;
diff --git a/runtime/vm/compiler/backend/sexpression_test.cc b/runtime/vm/compiler/backend/sexpression_test.cc
index db0b1ed..8c0edac 100644
--- a/runtime/vm/compiler/backend/sexpression_test.cc
+++ b/runtime/vm/compiler/backend/sexpression_test.cc
@@ -191,13 +191,13 @@
TextBuffer buf(100);
sexp->SerializeTo(zone, &buf, "", 9999);
- SExpression* round_trip = SExpression::FromCString(zone, buf.buf());
+ SExpression* round_trip = SExpression::FromCString(zone, buf.buffer());
CheckDeserializedSExpParts(round_trip);
EXPECT(sexp->Equals(round_trip));
char* const old_serialization = buf.Steal();
round_trip->SerializeTo(zone, &buf, "", 9999);
- char* const new_serialization = buf.buf();
+ char* const new_serialization = buf.buffer();
EXPECT_STREQ(old_serialization, new_serialization);
free(old_serialization);
}
diff --git a/runtime/vm/compiler/backend/slot.h b/runtime/vm/compiler/backend/slot.h
index f314bd3..f59bc7c 100644
--- a/runtime/vm/compiler/backend/slot.h
+++ b/runtime/vm/compiler/backend/slot.h
@@ -197,7 +197,7 @@
Slot(Kind kind,
int8_t bits,
- int16_t cid,
+ ClassIdTagType cid,
intptr_t offset_in_bytes,
const void* data,
const AbstractType* static_type)
@@ -229,7 +229,7 @@
const Kind kind_;
const int8_t flags_; // is_immutable, is_nullable
- const int16_t cid_; // Concrete cid of a value or kDynamicCid.
+ const ClassIdTagType cid_; // Concrete cid of a value or kDynamicCid.
const intptr_t offset_in_bytes_;
diff --git a/runtime/vm/compiler/backend/type_propagator.cc b/runtime/vm/compiler/backend/type_propagator.cc
index 8d2bb7a..f3fcd25 100644
--- a/runtime/vm/compiler/backend/type_propagator.cc
+++ b/runtime/vm/compiler/backend/type_propagator.cc
@@ -877,10 +877,10 @@
return CanPotentiallyBeSmi(*ToAbstractType(), /*recurse=*/true);
}
-void CompileType::PrintTo(BufferFormatter* f) const {
+void CompileType::PrintTo(BaseTextBuffer* f) const {
const char* type_name = "?";
if (IsNone()) {
- f->Print("T{}");
+ f->AddString("T{}");
return;
} else if ((cid_ != kIllegalCid) && (cid_ != kDynamicCid)) {
const Class& cls =
@@ -894,7 +894,7 @@
type_name = "!null";
}
- f->Print("T{%s%s}", type_name, is_nullable_ ? "?" : "");
+ f->Printf("T{%s%s}", type_name, is_nullable_ ? "?" : "");
}
const char* CompileType::ToCString() const {
diff --git a/runtime/vm/compiler/call_specializer.cc b/runtime/vm/compiler/call_specializer.cc
index c84bdaf..2c7f4dc 100644
--- a/runtime/vm/compiler/call_specializer.cc
+++ b/runtime/vm/compiler/call_specializer.cc
@@ -774,18 +774,16 @@
new (Z) Value(receiver), slot, call->token_pos(), calls_initializer,
calls_initializer ? call->deopt_id() : DeoptId::kNone);
- Environment* load_env = nullptr;
- if (calls_initializer) {
- // Drop getter argument from the environment as it is not
- // pushed on the stack when initializer is called.
- load_env =
- call->env()->DeepCopy(Z, call->env()->Length() - call->ArgumentCount());
+ // Note that this is a case of LoadField -> InstanceCall lazy deopt.
+ // Which means that we don't need to remove arguments from the environment
+ // because normal getter call expects receiver pushed (unlike the case
+ // of LoadField -> LoadField deoptimization handled by
+ // FlowGraph::AttachEnvironment).
+ if (!calls_initializer) {
+ // If we don't call initializer then we don't need an environment.
+ call->RemoveEnvironment();
}
- call->RemoveEnvironment();
ReplaceCall(call, load);
- if (calls_initializer) {
- load_env->DeepCopyTo(Z, load);
- }
if (load->slot().nullable_cid() != kDynamicCid) {
// Reset value types if we know concrete cid.
diff --git a/runtime/vm/compiler/compiler_pass.cc b/runtime/vm/compiler/compiler_pass.cc
index 691ef28..f253ffc 100644
--- a/runtime/vm/compiler/compiler_pass.cc
+++ b/runtime/vm/compiler/compiler_pass.cc
@@ -562,7 +562,7 @@
FlowGraphSerializer::SerializeToBuffer(stack_zone.GetZone(), flow_graph,
&buffer);
- file_write(buffer.buf(), buffer.length(), stream);
+ file_write(buffer.buffer(), buffer.length(), stream);
}
});
#endif
diff --git a/runtime/vm/compiler/ffi/native_location.cc b/runtime/vm/compiler/ffi/native_location.cc
index 0c7fb16..bbc762e 100644
--- a/runtime/vm/compiler/ffi/native_location.cc
+++ b/runtime/vm/compiler/ffi/native_location.cc
@@ -210,47 +210,46 @@
return compiler::Address(loc.base_register(), loc.offset_in_bytes());
}
-static void PrintRepresentations(BufferFormatter* f,
- const NativeLocation& loc) {
- f->Print(" ");
+static void PrintRepresentations(BaseTextBuffer* f, const NativeLocation& loc) {
+ f->AddString(" ");
loc.container_type().PrintTo(f);
if (!loc.container_type().Equals(loc.payload_type())) {
- f->Print("[");
+ f->AddString("[");
loc.payload_type().PrintTo(f);
- f->Print("]");
+ f->AddString("]");
}
}
-void NativeLocation::PrintTo(BufferFormatter* f) const {
- f->Print("I");
+void NativeLocation::PrintTo(BaseTextBuffer* f) const {
+ f->AddString("I");
PrintRepresentations(f, *this);
}
-void NativeRegistersLocation::PrintTo(BufferFormatter* f) const {
+void NativeRegistersLocation::PrintTo(BaseTextBuffer* f) const {
if (num_regs() == 1) {
- f->Print("%s", RegisterNames::RegisterName(regs_->At(0)));
+ f->Printf("%s", RegisterNames::RegisterName(regs_->At(0)));
} else {
- f->Print("(");
+ f->AddString("(");
for (intptr_t i = 0; i < num_regs(); i++) {
- if (i != 0) f->Print(", ");
- f->Print("%s", RegisterNames::RegisterName(regs_->At(i)));
+ if (i != 0) f->Printf(", ");
+ f->Printf("%s", RegisterNames::RegisterName(regs_->At(i)));
}
- f->Print(")");
+ f->AddString(")");
}
PrintRepresentations(f, *this);
}
-void NativeFpuRegistersLocation::PrintTo(BufferFormatter* f) const {
+void NativeFpuRegistersLocation::PrintTo(BaseTextBuffer* f) const {
switch (fpu_reg_kind()) {
case kQuadFpuReg:
- f->Print("%s", RegisterNames::FpuRegisterName(fpu_reg()));
+ f->Printf("%s", RegisterNames::FpuRegisterName(fpu_reg()));
break;
#if defined(TARGET_ARCH_ARM)
case kDoubleFpuReg:
- f->Print("%s", RegisterNames::FpuDRegisterName(fpu_d_reg()));
+ f->Printf("%s", RegisterNames::FpuDRegisterName(fpu_d_reg()));
break;
case kSingleFpuReg:
- f->Print("%s", RegisterNames::FpuSRegisterName(fpu_s_reg()));
+ f->Printf("%s", RegisterNames::FpuSRegisterName(fpu_s_reg()));
break;
#endif // defined(TARGET_ARCH_ARM)
default:
@@ -260,8 +259,8 @@
PrintRepresentations(f, *this);
}
-void NativeStackLocation::PrintTo(BufferFormatter* f) const {
- f->Print("S%+" Pd, offset_in_bytes_);
+void NativeStackLocation::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("S%+" Pd, offset_in_bytes_);
PrintRepresentations(f, *this);
}
diff --git a/runtime/vm/compiler/ffi/native_location.h b/runtime/vm/compiler/ffi/native_location.h
index 7db24e6..fefee76 100644
--- a/runtime/vm/compiler/ffi/native_location.h
+++ b/runtime/vm/compiler/ffi/native_location.h
@@ -16,7 +16,7 @@
namespace dart {
-class BufferFormatter;
+class BaseTextBuffer;
namespace compiler {
@@ -94,7 +94,7 @@
UNREACHABLE();
}
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
const char* ToCString() const;
const NativeRegistersLocation& AsRegisters() const;
@@ -169,7 +169,7 @@
virtual NativeRegistersLocation& Split(intptr_t index, Zone* zone) const;
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
virtual bool Equals(const NativeLocation& other) const;
@@ -254,7 +254,7 @@
bool IsLowestBits() const;
#endif // defined(TARGET_ARCH_ARM)
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
virtual bool Equals(const NativeLocation& other) const;
@@ -303,7 +303,7 @@
virtual NativeStackLocation& Split(intptr_t index, Zone* zone) const;
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
virtual bool Equals(const NativeLocation& other) const;
diff --git a/runtime/vm/compiler/ffi/native_type.cc b/runtime/vm/compiler/ffi/native_type.cc
index 57db124..e4daa47 100644
--- a/runtime/vm/compiler/ffi/native_type.cc
+++ b/runtime/vm/compiler/ffi/native_type.cc
@@ -316,12 +316,12 @@
}
}
-void NativeType::PrintTo(BufferFormatter* f) const {
- f->Print("I");
+void NativeType::PrintTo(BaseTextBuffer* f) const {
+ f->AddString("I");
}
-void NativeFundamentalType::PrintTo(BufferFormatter* f) const {
- f->Print("%s", FundamentalTypeToCString(representation_));
+void NativeFundamentalType::PrintTo(BaseTextBuffer* f) const {
+ f->Printf("%s", FundamentalTypeToCString(representation_));
}
const NativeType& NativeType::WidenTo4Bytes(Zone* zone) const {
diff --git a/runtime/vm/compiler/ffi/native_type.h b/runtime/vm/compiler/ffi/native_type.h
index 0eee4de..b0dc39b 100644
--- a/runtime/vm/compiler/ffi/native_type.h
+++ b/runtime/vm/compiler/ffi/native_type.h
@@ -17,7 +17,7 @@
namespace dart {
-class BufferFormatter;
+class BaseTextBuffer;
namespace compiler {
@@ -102,7 +102,7 @@
// Otherwise, return original representation.
const NativeType& WidenTo4Bytes(Zone* zone) const;
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
const char* ToCString() const;
virtual ~NativeType() {}
@@ -153,7 +153,7 @@
virtual bool Equals(const NativeType& other) const;
virtual NativeFundamentalType& Split(intptr_t part, Zone* zone) const;
- virtual void PrintTo(BufferFormatter* f) const;
+ virtual void PrintTo(BaseTextBuffer* f) const;
virtual ~NativeFundamentalType() {}
diff --git a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
index 2939eff..ee3a6bb 100644
--- a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
+++ b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
@@ -4750,19 +4750,12 @@
for (intptr_t i = 0; i < catch_count; ++i) {
intptr_t catch_offset = ReaderOffset(); // Catch has no tag.
TokenPosition position = ReadPosition(); // read position.
- Tag tag = PeekTag(); // peek guard type.
- AbstractType* type_guard = NULL;
- if (tag != kDynamicType) {
- type_guard = &T.BuildType(); // read guard.
- handler_types.SetAt(i, *type_guard);
- } else {
- SkipDartType(); // read guard.
- handler_types.SetAt(i, Object::dynamic_type());
- }
+ const AbstractType& type_guard = T.BuildType(); // read guard.
+ handler_types.SetAt(i, type_guard);
Fragment catch_handler_body = EnterScope(catch_offset);
- tag = ReadTag(); // read first part of exception.
+ Tag tag = ReadTag(); // read first part of exception.
if (tag == kSomething) {
catch_handler_body += LoadLocal(CurrentException());
catch_handler_body +=
@@ -4796,22 +4789,22 @@
}
}
- if (type_guard != NULL) {
+ if (!type_guard.IsCatchAllType()) {
catch_body += LoadLocal(CurrentException());
- if (!type_guard->IsInstantiated(kCurrentClass)) {
+ if (!type_guard.IsInstantiated(kCurrentClass)) {
catch_body += LoadInstantiatorTypeArguments();
} else {
catch_body += NullConstant();
}
- if (!type_guard->IsInstantiated(kFunctions)) {
+ if (!type_guard.IsInstantiated(kFunctions)) {
catch_body += LoadFunctionTypeArguments();
} else {
catch_body += NullConstant();
}
- catch_body += Constant(*type_guard);
+ catch_body += Constant(type_guard);
catch_body += InstanceCall(
position, Library::PrivateCoreLibName(Symbols::_instanceOf()),
diff --git a/runtime/vm/dart.cc b/runtime/vm/dart.cc
index 72d86d6..e419af5 100644
--- a/runtime/vm/dart.cc
+++ b/runtime/vm/dart.cc
@@ -855,7 +855,7 @@
}
b.AddString("End of function pool.\n\n");
}
- THR_Print("%s", b.buf());
+ THR_Print("%s", b.buffer());
}
#endif
diff --git a/runtime/vm/dart_api_impl.cc b/runtime/vm/dart_api_impl.cc
index 1b04132..f190dcc 100644
--- a/runtime/vm/dart_api_impl.cc
+++ b/runtime/vm/dart_api_impl.cc
@@ -1081,15 +1081,15 @@
Dart_FinalizableHandle object,
Dart_Handle strong_ref_to_object,
intptr_t external_allocation_size) {
- if (!Dart_IdentityEquals(strong_ref_to_object,
- HandleFromFinalizable(object))) {
+ if (!::Dart_IdentityEquals(strong_ref_to_object,
+ HandleFromFinalizable(object))) {
FATAL1(
"%s expects arguments 'object' and 'strong_ref_to_object' to point to "
"the same object.",
CURRENT_FUNC);
}
auto wph_object = reinterpret_cast<Dart_WeakPersistentHandle>(object);
- Dart_UpdateExternalSize(wph_object, external_allocation_size);
+ ::Dart_UpdateExternalSize(wph_object, external_allocation_size);
}
DART_EXPORT void Dart_DeletePersistentHandle(Dart_PersistentHandle object) {
@@ -1122,8 +1122,8 @@
DART_EXPORT void Dart_DeleteFinalizableHandle(
Dart_FinalizableHandle object,
Dart_Handle strong_ref_to_object) {
- if (!Dart_IdentityEquals(strong_ref_to_object,
- HandleFromFinalizable(object))) {
+ if (!::Dart_IdentityEquals(strong_ref_to_object,
+ HandleFromFinalizable(object))) {
FATAL1(
"%s expects arguments 'object' and 'strong_ref_to_object' to point to "
"the same object.",
@@ -1132,7 +1132,7 @@
auto wph_object = reinterpret_cast<Dart_WeakPersistentHandle>(object);
- return Dart_DeleteWeakPersistentHandle(wph_object);
+ ::Dart_DeleteWeakPersistentHandle(wph_object);
}
// --- Initialization and Globals ---
diff --git a/runtime/vm/dwarf.cc b/runtime/vm/dwarf.cc
index 8b927ec..da8bb08 100644
--- a/runtime/vm/dwarf.cc
+++ b/runtime/vm/dwarf.cc
@@ -774,7 +774,7 @@
i += offset;
}
if (!changed) return cstr;
- return OS::SCreate(zone_, "%s", buffer.buf());
+ return OS::SCreate(zone_, "%s", buffer.buffer());
}
Trie<const char>* Dwarf::CreateReverseObfuscationTrie(Zone* zone) {
diff --git a/runtime/vm/json_test.cc b/runtime/vm/json_test.cc
index d25d01d..db2e2f3 100644
--- a/runtime/vm/json_test.cc
+++ b/runtime/vm/json_test.cc
@@ -15,9 +15,9 @@
TEST_CASE(JSON_TextBuffer) {
TextBuffer w(5); // Small enough to make buffer grow at least once.
w.Printf("{ \"%s\" : %d", "length", 175);
- EXPECT_STREQ("{ \"length\" : 175", w.buf());
+ EXPECT_STREQ("{ \"length\" : 175", w.buffer());
w.Printf(", \"%s\" : \"%s\" }", "command", "stopIt");
- EXPECT_STREQ("{ \"length\" : 175, \"command\" : \"stopIt\" }", w.buf());
+ EXPECT_STREQ("{ \"length\" : 175, \"command\" : \"stopIt\" }", w.buffer());
}
TEST_CASE(JSON_JSONStream_Primitives) {
diff --git a/runtime/vm/json_writer.cc b/runtime/vm/json_writer.cc
index 587bf15..b0358f3 100644
--- a/runtime/vm/json_writer.cc
+++ b/runtime/vm/json_writer.cc
@@ -69,7 +69,7 @@
void JSONWriter::UncloseObject() {
intptr_t len = buffer_.length();
ASSERT(len > 0);
- ASSERT(buffer_.buf()[len - 1] == '}');
+ ASSERT(buffer_.buffer()[len - 1] == '}');
open_objects_++;
buffer_.set_length(len - 1);
}
@@ -315,7 +315,7 @@
}
bool JSONWriter::NeedComma() {
- const char* buffer = buffer_.buf();
+ const char* buffer = buffer_.buffer();
intptr_t length = buffer_.length();
if (length == 0) {
return false;
diff --git a/runtime/vm/json_writer.h b/runtime/vm/json_writer.h
index c9d4375..311e476 100644
--- a/runtime/vm/json_writer.h
+++ b/runtime/vm/json_writer.h
@@ -17,7 +17,7 @@
explicit JSONWriter(intptr_t buf_size = 256);
TextBuffer* buffer() { return &buffer_; }
- const char* ToCString() { return buffer_.buf(); }
+ const char* ToCString() { return buffer_.buffer(); }
void Steal(char** buffer, intptr_t* buffer_length);
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc
index e06504c..58327ce 100644
--- a/runtime/vm/object.cc
+++ b/runtime/vm/object.cc
@@ -8,6 +8,7 @@
#include "include/dart_api.h"
#include "platform/assert.h"
+#include "platform/text_buffer.h"
#include "platform/unaligned.h"
#include "platform/unicode.h"
#include "vm/bit_vector.h"
@@ -183,7 +184,7 @@
const double MegamorphicCache::kLoadFactor = 0.50;
-static void AppendSubString(ZoneTextBuffer* buffer,
+static void AppendSubString(BaseTextBuffer* buffer,
const char* name,
intptr_t start_pos,
intptr_t len) {
@@ -1051,6 +1052,7 @@
Smi::New(0));
empty_type_arguments_->StoreSmi(&empty_type_arguments_->raw_ptr()->hash_,
Smi::New(0));
+ empty_type_arguments_->ComputeHash();
empty_type_arguments_->SetCanonical();
}
@@ -4990,9 +4992,9 @@
ASSERT(!value.IsNull() && value.IsCanonical() && value.IsOld());
ASSERT((declaration_type() == Object::null()) ||
(declaration_type() == value.raw())); // Set during own finalization.
- // Since declaration type is used as the runtime type of instances of a
- // non-generic class, the nullability is set to kNonNullable instead of
- // kLegacy when the non-nullable experiment is enabled.
+ // Since DeclarationType is used as the runtime type of instances of a
+ // non-generic class, its nullability must be kNonNullable.
+ // The exception is DeclarationType of Null which is kNullable.
ASSERT(value.type_class_id() != kNullCid || value.IsNullable());
ASSERT(value.type_class_id() == kNullCid || value.IsNonNullable());
StorePointer(&raw_ptr()->declaration_type_, value.raw());
@@ -5862,14 +5864,13 @@
StoreSmi(&raw_ptr()->nullability_, Smi::New(value));
}
-intptr_t TypeArguments::ComputeHash() const {
- if (IsNull()) return 0;
- const intptr_t num_types = Length();
- if (IsRaw(0, num_types)) return 0;
+intptr_t TypeArguments::HashForRange(intptr_t from_index, intptr_t len) const {
+ if (IsNull()) return kAllDynamicHash;
+ if (IsRaw(from_index, len)) return kAllDynamicHash;
uint32_t result = 0;
AbstractType& type = AbstractType::Handle();
- for (intptr_t i = 0; i < num_types; i++) {
- type = TypeAt(i);
+ for (intptr_t i = 0; i < len; i++) {
+ type = TypeAt(from_index + i);
// The hash may be calculated during type finalization (for debugging
// purposes only) while a type argument is still temporarily null.
if (type.IsNull() || type.IsNullTypeRef()) {
@@ -5878,7 +5879,16 @@
result = CombineHashes(result, type.Hash());
}
result = FinalizeHash(result, kHashBits);
- SetHash(result);
+ return result;
+}
+
+intptr_t TypeArguments::ComputeHash() const {
+ if (IsNull()) return kAllDynamicHash;
+ const intptr_t num_types = Length();
+ const uint32_t result = HashForRange(0, num_types);
+ if (result != 0) {
+ SetHash(result);
+ }
return result;
}
@@ -5941,7 +5951,7 @@
intptr_t from_index,
intptr_t len,
NameVisibility name_visibility,
- ZoneTextBuffer* printer,
+ BaseTextBuffer* printer,
NameDisambiguation name_disambiguation /* = NameDisambiguation::kNo */)
const {
printer->AddString("<");
@@ -8900,7 +8910,7 @@
void Function::PrintSignatureParameters(Thread* thread,
Zone* zone,
NameVisibility name_visibility,
- ZoneTextBuffer* printer) const {
+ BaseTextBuffer* printer) const {
AbstractType& param_type = AbstractType::Handle(zone);
const intptr_t num_params = NumParameters();
const intptr_t num_fixed_params = num_fixed_parameters();
@@ -8941,7 +8951,7 @@
if (num_opt_named_params > 0) {
name = ParameterNameAt(i);
printer->AddString(" ");
- printer->AddString(name);
+ printer->AddString(name.ToCString());
}
if (i != (num_params - 1)) {
printer->AddString(", ");
@@ -8993,7 +9003,7 @@
}
void Function::PrintSignature(NameVisibility name_visibility,
- ZoneTextBuffer* printer) const {
+ BaseTextBuffer* printer) const {
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
Isolate* isolate = thread->isolate();
@@ -9279,7 +9289,7 @@
}
void Function::PrintName(const NameFormattingParams& params,
- ZoneTextBuffer* printer) const {
+ BaseTextBuffer* printer) const {
// If |this| is the generated asynchronous body closure, use the
// name of the parent function.
Function& fun = Function::Handle(raw());
@@ -14682,7 +14692,7 @@
}
const char* ExceptionHandlers::ToCString() const {
-#define FORMAT1 "%" Pd " => %#x (%" Pd " types) (outer %d) %s\n"
+#define FORMAT1 "%" Pd " => %#x (%" Pd " types) (outer %d)%s%s\n"
#define FORMAT2 " %d. %s\n"
if (num_entries() == 0) {
return "empty ExceptionHandlers\n";
@@ -14697,9 +14707,11 @@
handled_types = GetHandledTypes(i);
const intptr_t num_types =
handled_types.IsNull() ? 0 : handled_types.Length();
- len += Utils::SNPrint(NULL, 0, FORMAT1, i, info.handler_pc_offset,
- num_types, info.outer_try_index,
- info.is_generated != 0 ? "(generated)" : "");
+ len += Utils::SNPrint(
+ NULL, 0, FORMAT1, i, info.handler_pc_offset, num_types,
+ info.outer_try_index,
+ ((info.needs_stacktrace != 0) ? " (needs stack trace)" : ""),
+ ((info.is_generated != 0) ? " (generated)" : ""));
for (int k = 0; k < num_types; k++) {
type ^= handled_types.At(k);
ASSERT(!type.IsNull());
@@ -14715,10 +14727,11 @@
handled_types = GetHandledTypes(i);
const intptr_t num_types =
handled_types.IsNull() ? 0 : handled_types.Length();
- num_chars +=
- Utils::SNPrint((buffer + num_chars), (len - num_chars), FORMAT1, i,
- info.handler_pc_offset, num_types, info.outer_try_index,
- info.is_generated != 0 ? "(generated)" : "");
+ num_chars += Utils::SNPrint(
+ (buffer + num_chars), (len - num_chars), FORMAT1, i,
+ info.handler_pc_offset, num_types, info.outer_try_index,
+ ((info.needs_stacktrace != 0) ? " (needs stack trace)" : ""),
+ ((info.is_generated != 0) ? " (generated)" : ""));
for (int k = 0; k < num_types; k++) {
type ^= handled_types.At(k);
num_chars += Utils::SNPrint((buffer + num_chars), (len - num_chars),
@@ -19217,14 +19230,14 @@
void AbstractType::PrintName(
NameVisibility name_visibility,
- ZoneTextBuffer* printer,
+ BaseTextBuffer* printer,
NameDisambiguation name_disambiguation /* = NameDisambiguation::kNo */)
const {
ASSERT(name_visibility != kScrubbedName);
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
Class& cls = Class::Handle(zone);
- String& class_name = String::Handle(zone);
+ String& name_str = String::Handle(zone);
if (IsTypeParameter()) {
const TypeParameter& param = TypeParameter::Cast(*this);
@@ -19246,7 +19259,8 @@
}
}
- printer->AddString(String::Handle(zone, param.name()));
+ name_str = param.name();
+ printer->AddString(name_str.ToCString());
printer->AddString(NullabilitySuffix(name_visibility));
return;
}
@@ -19272,10 +19286,10 @@
}
// Instead of printing the actual signature, use the typedef name with
// its type arguments, if any.
- class_name = cls.Name(); // Typedef name.
+ name_str = cls.Name(); // Typedef name.
if (!IsFinalized() || IsBeingFinalized()) {
// TODO(regis): Check if this is dead code.
- printer->AddString(class_name);
+ printer->AddString(name_str.ToCString());
printer->AddString(NullabilitySuffix(name_visibility));
return;
}
@@ -19284,8 +19298,8 @@
// Do not print the full vector, but only the declared type parameters.
num_type_params = cls.NumTypeParameters();
if (name_visibility == kInternalName) {
- class_name = cls.Name();
- printer->AddString(class_name);
+ name_str = cls.Name();
+ printer->AddString(name_str.ToCString());
} else {
ASSERT(name_visibility == kUserVisibleName);
// Map internal types to their corresponding public interfaces.
@@ -20298,7 +20312,7 @@
intptr_t Type::ComputeHash() const {
ASSERT(IsFinalized());
- uint32_t result = 1;
+ uint32_t result = 0;
result = CombineHashes(result, type_class_id());
// A legacy type should have the same hash as its non-nullable version to be
// consistent with the definition of type equality in Dart code.
@@ -20307,7 +20321,20 @@
type_nullability = Nullability::kNonNullable;
}
result = CombineHashes(result, static_cast<uint32_t>(type_nullability));
- result = CombineHashes(result, TypeArguments::Handle(arguments()).Hash());
+ uint32_t type_args_hash = TypeArguments::kAllDynamicHash;
+ if (arguments() != TypeArguments::null()) {
+ // Only include hashes of type arguments corresponding to type parameters.
+ // This prevents obtaining different hashes depending on the location of
+ // TypeRefs in the super class type argument vector.
+ const TypeArguments& type_args = TypeArguments::Handle(arguments());
+ const Class& cls = Class::Handle(type_class());
+ const intptr_t num_type_params = cls.NumTypeParameters();
+ if (num_type_params > 0) {
+ const intptr_t from_index = cls.NumTypeArguments() - num_type_params;
+ type_args_hash = type_args.HashForRange(from_index, num_type_params);
+ }
+ }
+ result = CombineHashes(result, type_args_hash);
if (IsFunctionType()) {
AbstractType& type = AbstractType::Handle();
const Function& sig_fun = Function::Handle(signature());
@@ -21018,18 +21045,21 @@
const char* TypeParameter::ToCString() const {
Thread* thread = Thread::Current();
ZoneTextBuffer printer(thread->zone());
+ auto& name_str = String::Handle(thread->zone(), name());
printer.Printf("TypeParameter: name ");
- printer.AddString(String::Handle(name()));
+ printer.AddString(name_str.ToCString());
printer.AddString(NullabilitySuffix(kInternalName));
printer.Printf("; index: %" Pd ";", index());
if (IsFunctionTypeParameter()) {
const Function& function = Function::Handle(parameterized_function());
printer.Printf(" function: ");
- printer.AddString(String::Handle(function.name()));
+ name_str = function.name();
+ printer.AddString(name_str.ToCString());
} else {
const Class& cls = Class::Handle(parameterized_class());
printer.Printf(" class: ");
- printer.AddString(String::Handle(cls.Name()));
+ name_str = cls.Name();
+ printer.AddString(name_str.ToCString());
}
printer.Printf("; bound: ");
const AbstractType& upper_bound = AbstractType::Handle(bound());
@@ -24317,7 +24347,7 @@
#if defined(DART_PRECOMPILED_RUNTIME)
// Prints the best representation(s) for the call address.
-static void PrintNonSymbolicStackFrameBody(ZoneTextBuffer* buffer,
+static void PrintNonSymbolicStackFrameBody(BaseTextBuffer* buffer,
uword call_addr,
uword isolate_instructions,
uword vm_instructions,
@@ -24353,12 +24383,12 @@
}
#endif
-static void PrintSymbolicStackFrameIndex(ZoneTextBuffer* buffer,
+static void PrintSymbolicStackFrameIndex(BaseTextBuffer* buffer,
intptr_t frame_index) {
buffer->Printf("#%-6" Pd "", frame_index);
}
-static void PrintSymbolicStackFrameBody(ZoneTextBuffer* buffer,
+static void PrintSymbolicStackFrameBody(BaseTextBuffer* buffer,
const char* function_name,
const char* url,
intptr_t line = -1,
@@ -24374,7 +24404,7 @@
}
static void PrintSymbolicStackFrame(Zone* zone,
- ZoneTextBuffer* buffer,
+ BaseTextBuffer* buffer,
const Function& function,
TokenPosition token_pos,
intptr_t frame_index) {
diff --git a/runtime/vm/object.h b/runtime/vm/object.h
index ed97d50..2824547 100644
--- a/runtime/vm/object.h
+++ b/runtime/vm/object.h
@@ -71,7 +71,7 @@
#undef REUSABLE_FORWARD_DECLARATION
class Symbols;
-class ZoneTextBuffer;
+class BaseTextBuffer;
#if defined(DEBUG)
#define CHECK_HANDLE() CheckHandle();
@@ -2478,7 +2478,7 @@
const char* NameCString(NameVisibility name_visibility) const;
void PrintName(const NameFormattingParams& params,
- ZoneTextBuffer* printer) const;
+ BaseTextBuffer* printer) const;
StringPtr QualifiedScrubbedName() const;
StringPtr QualifiedUserVisibleName() const;
@@ -2552,7 +2552,7 @@
StringPtr UserVisibleSignature() const;
void PrintSignature(NameVisibility name_visibility,
- ZoneTextBuffer* printer) const;
+ BaseTextBuffer* printer) const;
// Returns true if the signature of this function is instantiated, i.e. if it
// does not involve generic parameter types or generic result type.
@@ -3792,7 +3792,7 @@
void PrintSignatureParameters(Thread* thread,
Zone* zone,
NameVisibility name_visibility,
- ZoneTextBuffer* printer) const;
+ BaseTextBuffer* printer) const;
// Returns true if the type of the formal parameter at the given position in
// this function is contravariant with the type of the other formal parameter
@@ -7528,6 +7528,9 @@
// architecture.
static const intptr_t kHashBits = 30;
+ // Hash value for a type argument vector consisting solely of dynamic types.
+ static const intptr_t kAllDynamicHash = 1;
+
intptr_t Length() const;
AbstractTypePtr TypeAt(intptr_t index) const;
AbstractTypePtr TypeAtNullSafe(intptr_t index) const;
@@ -7583,7 +7586,7 @@
intptr_t from_index,
intptr_t len,
NameVisibility name_visibility,
- ZoneTextBuffer* printer,
+ BaseTextBuffer* printer,
NameDisambiguation name_disambiguation = NameDisambiguation::kNo) const;
// Check if the subvector of length 'len' starting at 'from_index' of this
@@ -7742,6 +7745,7 @@
return 0;
}
intptr_t Hash() const;
+ intptr_t HashForRange(intptr_t from_index, intptr_t len) const;
static TypeArgumentsPtr New(intptr_t len, Heap::Space space = Heap::kOld);
@@ -7910,7 +7914,7 @@
// type arguments, if any.
void PrintName(
NameVisibility visibility,
- ZoneTextBuffer* printer,
+ BaseTextBuffer* printer,
NameDisambiguation name_disambiguation = NameDisambiguation::kNo) const;
// Add the class name and URI of each occuring type to the uris
@@ -7997,6 +8001,11 @@
// Returns unmodified type if this type is not a 'FutureOr' type.
AbstractTypePtr UnwrapFutureOr() const;
+ // Returns true if catching this type will catch all exceptions.
+ // Exception objects are guaranteed to be non-nullable, so
+ // non-nullable Object is also a catch-all type.
+ bool IsCatchAllType() const { return IsDynamicType() || IsObjectType(); }
+
// Check the subtype relationship.
bool IsSubtypeOf(const AbstractType& other,
Heap::Space space,
@@ -11321,7 +11330,7 @@
}
inline intptr_t TypeArguments::Hash() const {
- if (IsNull()) return 0;
+ if (IsNull()) return kAllDynamicHash;
intptr_t result = Smi::Value(raw_ptr()->hash_);
if (result != 0) {
return result;
diff --git a/runtime/vm/object_graph.cc b/runtime/vm/object_graph.cc
index 901efba..e127267 100644
--- a/runtime/vm/object_graph.cc
+++ b/runtime/vm/object_graph.cc
@@ -643,7 +643,7 @@
}
Service::SendEventWithData(Service::heapsnapshot_stream.id(), "HeapSnapshot",
- kMetadataReservation, js.buffer()->buf(),
+ kMetadataReservation, js.buffer()->buffer(),
js.buffer()->length(), buffer_, size_);
buffer_ = nullptr;
size_ = 0;
diff --git a/runtime/vm/raw_object.h b/runtime/vm/raw_object.h
index 3e634e4..afcf33d 100644
--- a/runtime/vm/raw_object.h
+++ b/runtime/vm/raw_object.h
@@ -138,8 +138,6 @@
// See Object::MakeUnusedSpaceTraversable.
COMPILE_ASSERT(kCardRememberedBit == 0);
- COMPILE_ASSERT(8 * sizeof(uint16_t) == kClassIdTagSize);
-
// Encodes the object size in the tag in units of object alignment.
class SizeTag {
public:
@@ -181,8 +179,11 @@
}
};
- class ClassIdTag
- : public BitField<uint32_t, intptr_t, kClassIdTagPos, kClassIdTagSize> {};
+ class ClassIdTag : public BitField<uint32_t,
+ ClassIdTagType,
+ kClassIdTagPos,
+ kClassIdTagSize> {};
+ COMPILE_ASSERT(kBitsPerByte * sizeof(ClassIdTagType) == kClassIdTagSize);
class CardRememberedBit
: public BitField<uint32_t, bool, kCardRememberedBit, 1> {};
@@ -1195,9 +1196,9 @@
#endif
TokenPosition token_pos_;
TokenPosition end_token_pos_;
- uint16_t guarded_cid_;
- uint16_t is_nullable_; // kNullCid if field can contain null value and
- // kInvalidCid otherwise.
+ ClassIdTagType guarded_cid_;
+ ClassIdTagType is_nullable_; // kNullCid if field can contain null value and
+ // kInvalidCid otherwise.
#if !defined(DART_PRECOMPILED_RUNTIME)
typedef BitField<uint32_t, bool, 0, 1> IsDeclaredInBytecode;
@@ -1402,7 +1403,7 @@
#if defined(DART_PRECOMPILED_RUNTIME)
VISIT_NOTHING();
- uint16_t cid_;
+ ClassIdTagType cid_;
#else
VISIT_FROM(ObjectPtr, target_);
ObjectPtr target_;
@@ -1988,8 +1989,8 @@
CodePtr target_;
VISIT_TO(ObjectPtr, target_);
uword entry_point_;
- uint16_t lower_limit_;
- uint16_t upper_limit_;
+ ClassIdTagType lower_limit_;
+ ClassIdTagType upper_limit_;
};
class MonomorphicSmiableCallLayout : public ObjectLayout {
@@ -2256,7 +2257,7 @@
AbstractTypePtr bound_; // ObjectType if no explicit bound specified.
FunctionPtr parameterized_function_;
VISIT_TO(ObjectPtr, parameterized_function_)
- uint16_t parameterized_class_id_;
+ ClassIdTagType parameterized_class_id_;
TokenPosition token_pos_;
int16_t index_;
uint8_t flags_;
diff --git a/runtime/vm/service.cc b/runtime/vm/service.cc
index 3b7af8f..f82c430 100644
--- a/runtime/vm/service.cc
+++ b/runtime/vm/service.cc
@@ -1142,7 +1142,7 @@
event->stream_info()->consumer() != nullptr) {
auto length = js.buffer()->length();
event->stream_info()->consumer()(
- reinterpret_cast<uint8_t*>(js.buffer()->buf()), length);
+ reinterpret_cast<uint8_t*>(js.buffer()->buffer()), length);
}
}
@@ -1623,8 +1623,9 @@
data[reservation + 0] = 0;
data[reservation + 1] = 128;
data[reservation + 2] = 255;
- SendEventWithData(echo_stream.id(), "_Echo", reservation, js.buffer()->buf(),
- js.buffer()->length(), data, data_size);
+ SendEventWithData(echo_stream.id(), "_Echo", reservation,
+ js.buffer()->buffer(), js.buffer()->length(), data,
+ data_size);
}
static bool TriggerEchoEvent(Thread* thread, JSONStream* js) {
diff --git a/runtime/vm/version.h b/runtime/vm/version.h
index a3769f6..cab6c26 100644
--- a/runtime/vm/version.h
+++ b/runtime/vm/version.h
@@ -14,8 +14,6 @@
static const char* String();
static const char* SnapshotString();
static const char* CommitString();
- static int CurrentAbiVersion();
- static int OldestSupportedAbiVersion();
static const char* SdkHash();
private:
diff --git a/runtime/vm/version_in.cc b/runtime/vm/version_in.cc
index f63fe3f..2fcf5c5 100644
--- a/runtime/vm/version_in.cc
+++ b/runtime/vm/version_in.cc
@@ -5,7 +5,6 @@
#include "vm/version.h"
#include "vm/cpu.h"
-#include "vm/flags.h"
#include "vm/os.h"
namespace dart {
@@ -30,14 +29,6 @@
return commit_;
}
-int Version::CurrentAbiVersion() {
- return {{ABI_VERSION}};
-}
-
-int Version::OldestSupportedAbiVersion() {
- return {{OLDEST_SUPPORTED_ABI_VERSION}};
-}
-
const char* Version::SdkHash() {
return git_short_hash_;
}
diff --git a/runtime/vm/zone_text_buffer.cc b/runtime/vm/zone_text_buffer.cc
index 446f952..f265937 100644
--- a/runtime/vm/zone_text_buffer.cc
+++ b/runtime/vm/zone_text_buffer.cc
@@ -14,51 +14,13 @@
namespace dart {
ZoneTextBuffer::ZoneTextBuffer(Zone* zone, intptr_t initial_capacity)
- : zone_(zone), buffer_(NULL), length_(0), capacity_(0) {
+ : zone_(zone) {
ASSERT(initial_capacity > 0);
buffer_ = reinterpret_cast<char*>(zone->Alloc<char>(initial_capacity));
capacity_ = initial_capacity;
buffer_[length_] = '\0';
}
-intptr_t ZoneTextBuffer::Printf(const char* format, ...) {
- va_list args;
- va_start(args, format);
- intptr_t remaining = capacity_ - length_;
- ASSERT(remaining >= 0);
- intptr_t len = Utils::VSNPrint(buffer_ + length_, remaining, format, args);
- va_end(args);
- if (len >= remaining) {
- EnsureCapacity(len);
- remaining = capacity_ - length_;
- ASSERT(remaining > len);
- va_list args2;
- va_start(args2, format);
- intptr_t len2 =
- Utils::VSNPrint(buffer_ + length_, remaining, format, args2);
- va_end(args2);
- ASSERT(len == len2);
- }
- length_ += len;
- buffer_[length_] = '\0';
- return len;
-}
-
-void ZoneTextBuffer::AddChar(char ch) {
- EnsureCapacity(sizeof(ch));
- buffer_[length_] = ch;
- length_++;
- buffer_[length_] = '\0';
-}
-
-void ZoneTextBuffer::AddString(const char* s) {
- Printf("%s", s);
-}
-
-void ZoneTextBuffer::AddString(const String& s) {
- Printf("%s", s.ToCString());
-}
-
void ZoneTextBuffer::Clear() {
const intptr_t initial_capacity = 64;
buffer_ = reinterpret_cast<char*>(zone_->Alloc<char>(initial_capacity));
@@ -67,13 +29,14 @@
buffer_[length_] = '\0';
}
-void ZoneTextBuffer::EnsureCapacity(intptr_t len) {
+bool ZoneTextBuffer::EnsureCapacity(intptr_t len) {
intptr_t remaining = capacity_ - length_;
if (remaining <= len) {
intptr_t new_capacity = capacity_ + Utils::Maximum(capacity_, len);
buffer_ = zone_->Realloc<char>(buffer_, capacity_, new_capacity);
capacity_ = new_capacity;
}
+ return true;
}
} // namespace dart
diff --git a/runtime/vm/zone_text_buffer.h b/runtime/vm/zone_text_buffer.h
index 1b7fef3..21e6739 100644
--- a/runtime/vm/zone_text_buffer.h
+++ b/runtime/vm/zone_text_buffer.h
@@ -5,6 +5,7 @@
#ifndef RUNTIME_VM_ZONE_TEXT_BUFFER_H_
#define RUNTIME_VM_ZONE_TEXT_BUFFER_H_
+#include "platform/text_buffer.h"
#include "vm/allocation.h"
#include "vm/globals.h"
@@ -13,29 +14,22 @@
class String;
class Zone;
-// TextBuffer maintains a dynamic character buffer with a printf-style way to
-// append text.
-class ZoneTextBuffer : ValueObject {
+// ZoneTextBuffer allocates the character buffer in the given zone. Thus,
+// pointers returned by buffer() have the same lifetime as the zone.
+class ZoneTextBuffer : public BaseTextBuffer {
public:
explicit ZoneTextBuffer(Zone* zone, intptr_t initial_capacity = 64);
~ZoneTextBuffer() {}
- intptr_t Printf(const char* format, ...) PRINTF_ATTRIBUTE(2, 3);
- void AddChar(char ch);
- void AddString(const char* s);
- void AddString(const String& s);
-
- char* buffer() { return buffer_; }
- intptr_t length() const { return length_; }
-
+ // Allocates a new internal buffer. Thus, the contents of buffers returned by
+ // previous calls to buffer() are no longer affected by this object.
void Clear();
private:
- void EnsureCapacity(intptr_t len);
+ bool EnsureCapacity(intptr_t len);
Zone* zone_;
- char* buffer_;
- intptr_t length_;
- intptr_t capacity_;
+
+ DISALLOW_COPY_AND_ASSIGN(ZoneTextBuffer);
};
} // namespace dart
diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn
index ea136e6..4e327d9 100644
--- a/sdk/BUILD.gn
+++ b/sdk/BUILD.gn
@@ -616,12 +616,6 @@
outputs = [ "$root_out_dir/dart-sdk/lib/_internal/{{source_file_part}}" ]
}
-copy("copy_abi_dill_files") {
- visibility = [ ":create_sdk_with_abi_versions" ]
- sources = [ "../tools/abiversions" ]
- outputs = [ "$root_out_dir/dart-sdk/lib/_internal/abiversions" ]
-}
-
copy("copy_dart2js_dill_files") {
visibility = [ ":create_full_sdk" ]
deps = [
@@ -968,11 +962,3 @@
public_deps += [ ":create_full_sdk" ]
}
}
-
-# Same as create_sdk, but with abi version files.
-group("create_sdk_with_abi_versions") {
- public_deps = [
- ":copy_abi_dill_files",
- ":create_sdk",
- ]
-}
diff --git a/sdk/lib/_http/http_parser.dart b/sdk/lib/_http/http_parser.dart
index 9459789..cb13b24 100644
--- a/sdk/lib/_http/http_parser.dart
+++ b/sdk/lib/_http/http_parser.dart
@@ -978,7 +978,6 @@
static bool _isValueChar(int byte) {
return (byte > 31 && byte < 128) ||
- (byte == _CharCode.SP) ||
(byte == _CharCode.HT);
}
diff --git a/tests/dart2js/jsinterop_test.dart b/tests/dart2js/jsinterop_test.dart
index f44b2b4..397f5e2 100644
--- a/tests/dart2js/jsinterop_test.dart
+++ b/tests/dart2js/jsinterop_test.dart
@@ -58,16 +58,16 @@
// NON_NATIVE_EXTERNAL //# 09: compile-time error
external factory Class.externalFact(); //# 09: continued
- @JS('a') // GENERIC //# 10: compile-time error
+ @JS('a') // GENERIC, GENERIC //# 10: compile-time error
Class.jsInteropGenerative(); //# 10: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 11: compile-time error
+ @JS('a') // GENERIC //# 11: compile-time error
factory Class.jsInteropFact() => null; //# 11: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 12: compile-time error
+ @JS('a') // GENERIC //# 12: compile-time error
external Class.externalJsInteropGenerative(); //# 12: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 13: compile-time error
+ @JS('a') // GENERIC //# 13: compile-time error
external factory Class.externalJsInteropFact(); //# 13: continued
var instanceField;
@@ -80,28 +80,28 @@
static set staticSetter(_) {}
static staticMethod() {}
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 14: compile-time error
+ @JS('a') // GENERIC //# 14: compile-time error
var instanceJsInteropField; //# 14: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 15: compile-time error
+ @JS('a') // GENERIC //# 15: compile-time error
get instanceJsInteropGetter => null; //# 15: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 16: compile-time error
+ @JS('a') // GENERIC //# 16: compile-time error
set instanceJsInteropSetter(_) {} //# 16: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 17: compile-time error
+ @JS('a') // GENERIC //# 17: compile-time error
instanceJsInteropMethod() {} //# 17: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 18: compile-time error
+ @JS('a') // GENERIC //# 18: compile-time error
static var staticJsInteropField; //# 18: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 19: compile-time error
+ @JS('a') // GENERIC //# 19: compile-time error
static get staticJsInteropGetter => null; //# 19: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 20: compile-time error
+ @JS('a') // GENERIC //# 20: compile-time error
static set staticJsInteropSetter(_) {} //# 20: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 21: compile-time error
+ @JS('a') // GENERIC //# 21: compile-time error
static staticJsInteropMethod() {} //# 21: continued
// NON_NATIVE_EXTERNAL //# 22: compile-time error
@@ -122,22 +122,22 @@
// NON_NATIVE_EXTERNAL //# 27: compile-time error
external static externalStaticMethod(); //# 27: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 28: compile-time error
+ @JS('a') // GENERIC //# 28: compile-time error
external get externalInstanceJsInteropGetter; //# 28: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 29: compile-time error
+ @JS('a') // GENERIC //# 29: compile-time error
external set externalInstanceJsInteropSetter(_); //# 29: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 30: compile-time error
+ @JS('a') // GENERIC //# 30: compile-time error
external externalInstanceJsInteropMethod(); //# 30: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 31: compile-time error
+ @JS('a') // GENERIC //# 31: compile-time error
external static get externalStaticJsInteropGetter; //# 31: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 32: compile-time error
+ @JS('a') // GENERIC //# 32: compile-time error
external static set externalStaticJsInteropSetter(_); //# 32: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 33: compile-time error
+ @JS('a') // GENERIC //# 33: compile-time error
external static externalStaticJsInteropMethod(); //# 33: continued
}
diff --git a/tests/dart2js/non_jsinterop_test.dart b/tests/dart2js/non_jsinterop_test.dart
index 67f239b..68eebe7 100644
--- a/tests/dart2js/non_jsinterop_test.dart
+++ b/tests/dart2js/non_jsinterop_test.dart
@@ -60,16 +60,16 @@
// NON_NATIVE_EXTERNAL //# 09: compile-time error
external factory Class.externalFact(); //# 09: continued
- @JS('a') // GENERIC //# 10: compile-time error
+ @JS('a') // GENERIC, GENERIC //# 10: compile-time error
Class.jsInteropGenerative(); //# 10: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 11: compile-time error
+ @JS('a') // GENERIC //# 11: compile-time error
factory Class.jsInteropFact() => null; //# 11: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 12: compile-time error
+ @JS('a') // GENERIC //# 12: compile-time error
external Class.externalJsInteropGenerative(); //# 12: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 13: compile-time error
+ @JS('a') // GENERIC //# 13: compile-time error
external factory Class.externalJsInteropFact(); //# 13: continued
var instanceField;
@@ -82,28 +82,28 @@
static set staticSetter(_) {}
static staticMethod() {}
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 14: compile-time error
+ @JS('a') // GENERIC //# 14: compile-time error
var instanceJsInteropField; //# 14: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 15: compile-time error
+ @JS('a') // GENERIC //# 15: compile-time error
get instanceJsInteropGetter => null; //# 15: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 16: compile-time error
+ @JS('a') // GENERIC //# 16: compile-time error
set instanceJsInteropSetter(_) {} //# 16: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 17: compile-time error
+ @JS('a') // GENERIC //# 17: compile-time error
instanceJsInteropMethod() {} //# 17: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 18: compile-time error
+ @JS('a') // GENERIC //# 18: compile-time error
static var staticJsInteropField; //# 18: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 19: compile-time error
+ @JS('a') // GENERIC //# 19: compile-time error
static get staticJsInteropGetter => null; //# 19: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 20: compile-time error
+ @JS('a') // GENERIC //# 20: compile-time error
static set staticJsInteropSetter(_) {} //# 20: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 21: compile-time error
+ @JS('a') // GENERIC //# 21: compile-time error
static staticJsInteropMethod() {} //# 21: continued
// NON_NATIVE_EXTERNAL //# 22: compile-time error
@@ -124,22 +124,22 @@
// NON_NATIVE_EXTERNAL //# 27: compile-time error
external static externalStaticMethod(); //# 27: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 28: compile-time error
+ @JS('a') // GENERIC //# 28: compile-time error
external get externalInstanceJsInteropGetter; //# 28: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 29: compile-time error
+ @JS('a') // GENERIC //# 29: compile-time error
external set externalInstanceJsInteropSetter(_); //# 29: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 30: compile-time error
+ @JS('a') // GENERIC //# 30: compile-time error
external externalInstanceJsInteropMethod(); //# 30: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 31: compile-time error
+ @JS('a') // GENERIC //# 31: compile-time error
external static get externalStaticJsInteropGetter; //# 31: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 32: compile-time error
+ @JS('a') // GENERIC //# 32: compile-time error
external static set externalStaticJsInteropSetter(_); //# 32: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 33: compile-time error
+ @JS('a') // GENERIC //# 33: compile-time error
external static externalStaticJsInteropMethod(); //# 33: continued
}
diff --git a/tests/dart2js_2/jsinterop_test.dart b/tests/dart2js_2/jsinterop_test.dart
index 23521a0..2db564c 100644
--- a/tests/dart2js_2/jsinterop_test.dart
+++ b/tests/dart2js_2/jsinterop_test.dart
@@ -60,16 +60,16 @@
// NON_NATIVE_EXTERNAL //# 09: compile-time error
external factory Class.externalFact(); //# 09: continued
- @JS('a') // GENERIC //# 10: compile-time error
+ @JS('a') // GENERIC, GENERIC //# 10: compile-time error
Class.jsInteropGenerative(); //# 10: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 11: compile-time error
+ @JS('a') // GENERIC //# 11: compile-time error
factory Class.jsInteropFact() => null; //# 11: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 12: compile-time error
+ @JS('a') // GENERIC //# 12: compile-time error
external Class.externalJsInteropGenerative(); //# 12: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 13: compile-time error
+ @JS('a') // GENERIC //# 13: compile-time error
external factory Class.externalJsInteropFact(); //# 13: continued
var instanceField;
@@ -82,28 +82,28 @@
static set staticSetter(_) {}
static staticMethod() {}
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 14: compile-time error
+ @JS('a') // GENERIC //# 14: compile-time error
var instanceJsInteropField; //# 14: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 15: compile-time error
+ @JS('a') // GENERIC //# 15: compile-time error
get instanceJsInteropGetter => null; //# 15: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 16: compile-time error
+ @JS('a') // GENERIC //# 16: compile-time error
set instanceJsInteropSetter(_) {} //# 16: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 17: compile-time error
+ @JS('a') // GENERIC //# 17: compile-time error
instanceJsInteropMethod() {} //# 17: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 18: compile-time error
+ @JS('a') // GENERIC //# 18: compile-time error
static var staticJsInteropField; //# 18: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 19: compile-time error
+ @JS('a') // GENERIC //# 19: compile-time error
static get staticJsInteropGetter => null; //# 19: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 20: compile-time error
+ @JS('a') // GENERIC //# 20: compile-time error
static set staticJsInteropSetter(_) {} //# 20: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 21: compile-time error
+ @JS('a') // GENERIC //# 21: compile-time error
static staticJsInteropMethod() {} //# 21: continued
// NON_NATIVE_EXTERNAL //# 22: compile-time error
@@ -124,22 +124,22 @@
// NON_NATIVE_EXTERNAL //# 27: compile-time error
external static externalStaticMethod(); //# 27: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 28: compile-time error
+ @JS('a') // GENERIC //# 28: compile-time error
external get externalInstanceJsInteropGetter; //# 28: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 29: compile-time error
+ @JS('a') // GENERIC //# 29: compile-time error
external set externalInstanceJsInteropSetter(_); //# 29: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 30: compile-time error
+ @JS('a') // GENERIC //# 30: compile-time error
external externalInstanceJsInteropMethod(); //# 30: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 31: compile-time error
+ @JS('a') // GENERIC //# 31: compile-time error
external static get externalStaticJsInteropGetter; //# 31: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 32: compile-time error
+ @JS('a') // GENERIC //# 32: compile-time error
external static set externalStaticJsInteropSetter(_); //# 32: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 33: compile-time error
+ @JS('a') // GENERIC //# 33: compile-time error
external static externalStaticJsInteropMethod(); //# 33: continued
}
diff --git a/tests/dart2js_2/non_jsinterop_test.dart b/tests/dart2js_2/non_jsinterop_test.dart
index bbaae2c..1bac858 100644
--- a/tests/dart2js_2/non_jsinterop_test.dart
+++ b/tests/dart2js_2/non_jsinterop_test.dart
@@ -62,16 +62,16 @@
// NON_NATIVE_EXTERNAL //# 09: compile-time error
external factory Class.externalFact(); //# 09: continued
- @JS('a') // GENERIC //# 10: compile-time error
+ @JS('a') // GENERIC, GENERIC //# 10: compile-time error
Class.jsInteropGenerative(); //# 10: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 11: compile-time error
+ @JS('a') // GENERIC //# 11: compile-time error
factory Class.jsInteropFact() => null; //# 11: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 12: compile-time error
+ @JS('a') // GENERIC //# 12: compile-time error
external Class.externalJsInteropGenerative(); //# 12: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 13: compile-time error
+ @JS('a') // GENERIC //# 13: compile-time error
external factory Class.externalJsInteropFact(); //# 13: continued
var instanceField;
@@ -84,28 +84,28 @@
static set staticSetter(_) {}
static staticMethod() {}
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 14: compile-time error
+ @JS('a') // GENERIC //# 14: compile-time error
var instanceJsInteropField; //# 14: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 15: compile-time error
+ @JS('a') // GENERIC //# 15: compile-time error
get instanceJsInteropGetter => null; //# 15: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 16: compile-time error
+ @JS('a') // GENERIC //# 16: compile-time error
set instanceJsInteropSetter(_) {} //# 16: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 17: compile-time error
+ @JS('a') // GENERIC //# 17: compile-time error
instanceJsInteropMethod() {} //# 17: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 18: compile-time error
+ @JS('a') // GENERIC //# 18: compile-time error
static var staticJsInteropField; //# 18: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 19: compile-time error
+ @JS('a') // GENERIC //# 19: compile-time error
static get staticJsInteropGetter => null; //# 19: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 20: compile-time error
+ @JS('a') // GENERIC //# 20: compile-time error
static set staticJsInteropSetter(_) {} //# 20: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 21: compile-time error
+ @JS('a') // GENERIC //# 21: compile-time error
static staticJsInteropMethod() {} //# 21: continued
// NON_NATIVE_EXTERNAL //# 22: compile-time error
@@ -126,22 +126,22 @@
// NON_NATIVE_EXTERNAL //# 27: compile-time error
external static externalStaticMethod(); //# 27: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 28: compile-time error
+ @JS('a') // GENERIC //# 28: compile-time error
external get externalInstanceJsInteropGetter; //# 28: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 29: compile-time error
+ @JS('a') // GENERIC //# 29: compile-time error
external set externalInstanceJsInteropSetter(_); //# 29: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 30: compile-time error
+ @JS('a') // GENERIC //# 30: compile-time error
external externalInstanceJsInteropMethod(); //# 30: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 31: compile-time error
+ @JS('a') // GENERIC //# 31: compile-time error
external static get externalStaticJsInteropGetter; //# 31: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 32: compile-time error
+ @JS('a') // GENERIC //# 32: compile-time error
external static set externalStaticJsInteropSetter(_); //# 32: continued
- @JS('a') // JS_INTEROP_MEMBER_IN_NON_JS_INTEROP_CLASS //# 33: compile-time error
+ @JS('a') // GENERIC //# 33: compile-time error
external static externalStaticJsInteropMethod(); //# 33: continued
}
diff --git a/tests/language/constructor/missing_initializer_test.dart b/tests/language/constructor/missing_initializer_test.dart
new file mode 100644
index 0000000..3604aa8
--- /dev/null
+++ b/tests/language/constructor/missing_initializer_test.dart
@@ -0,0 +1,49 @@
+// Copyright (c) 2020, 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.
+
+// Test that it is an error for a class with no generative constructors to
+// have a final instance variable without an initializing expression, except
+// if it is `abstract` or `external`. The latter also holds in a class with
+// generative constructors.
+
+// Has factory, hence no default, hence no generative constructors.
+abstract class A {
+ final dynamic n;
+ // ^
+ // [analyzer] COMPILE_TIME_ERROR.FINAL_NOT_INITIALIZED
+ // [cfe] unspecified
+
+ // Uninitialized, but no errors.
+ abstract final int x1;
+ abstract final int? x2;
+ external final String x3;
+ external final String? x4;
+
+ factory A() = B;
+}
+
+class B implements A {
+ dynamic get n => 1;
+ int get x1 => 1;
+ int? get x2 => null;
+ String get x3 => "";
+ String? get x4 => null;
+}
+
+class C = Object with A;
+
+// Has a generative constructor: default.
+abstract class D {
+ // Uninitialized, but no errors.
+ abstract final int x1;
+ abstract final int? x2;
+ external final String x3;
+ external final String? x4;
+}
+
+void main() {
+ A();
+ C();
+ var _ = D;
+}
diff --git a/tests/language/regress/regress42954_test.dart b/tests/language/regress/regress42954_test.dart
new file mode 100644
index 0000000..93c5d2b
--- /dev/null
+++ b/tests/language/regress/regress42954_test.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2020, 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:expect/expect.dart";
+
+class A<T> {
+ Type get type => T;
+}
+
+class B extends A<B> {}
+
+void main() {
+ var first = B;
+ var second = B().type;
+
+ Expect.equals(first, second);
+ Expect.equals(second, first);
+ Expect.equals(first.hashCode, second.hashCode);
+}
diff --git a/tests/language/vm/deopt_during_field_init_test.dart b/tests/language/vm/deopt_during_field_init_test.dart
new file mode 100644
index 0000000..6fb6f78
--- /dev/null
+++ b/tests/language/vm/deopt_during_field_init_test.dart
@@ -0,0 +1,42 @@
+// Copyright (c) 2020, 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.
+// Test that we don't hit unbalanced stack after deoptimization from LoadField
+// back to getter call.
+
+// VMOptions=--no-use-osr --optimization-counter-threshold=10 --no-background-compilation
+
+int counter = 0;
+
+class A {
+ late final Object field = init();
+
+ @pragma('vm:never-inline')
+ int init() {
+ counter++;
+ if (counter > 20) {
+ finalizeB();
+ }
+ return counter;
+ }
+}
+
+class B extends A {
+ final Object field = "Foo";
+}
+
+@pragma('vm:never-inline')
+finalizeB() {
+ print(new B().field);
+}
+
+@pragma('vm:never-inline')
+test(A a) {
+ print(a.field);
+}
+
+main() {
+ for (var i = 0; i < 100; i++) {
+ test(new A());
+ }
+}
diff --git a/tests/language_2/regress/regress42946_test.dart b/tests/language_2/regress/regress42946_test.dart
new file mode 100644
index 0000000..008793f
--- /dev/null
+++ b/tests/language_2/regress/regress42946_test.dart
@@ -0,0 +1,21 @@
+// Copyright (c) 2020, 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:expect/expect.dart';
+
+/// https://github.com/dart-lang/sdk/issues/42946
+void main() {
+ // fix bug in constant eval
+ const x = (2.0 == 2);
+ const a = (2.0 == 2.0);
+ const b = (0.0 == 0.0);
+ const c = (double.nan == double.nan);
+ const d = (2.0 == 1.0);
+
+ Expect.isTrue(x);
+ Expect.isTrue(a);
+ Expect.isTrue(b);
+ Expect.isFalse(c);
+ Expect.isFalse(d);
+}
diff --git a/tests/language_2/regress/regress42954_test.dart b/tests/language_2/regress/regress42954_test.dart
new file mode 100644
index 0000000..93c5d2b
--- /dev/null
+++ b/tests/language_2/regress/regress42954_test.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2020, 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:expect/expect.dart";
+
+class A<T> {
+ Type get type => T;
+}
+
+class B extends A<B> {}
+
+void main() {
+ var first = B;
+ var second = B().type;
+
+ Expect.equals(first, second);
+ Expect.equals(second, first);
+ Expect.equals(first.hashCode, second.hashCode);
+}
diff --git a/tests/lib/html/js_typed_interop_type_test.dart b/tests/lib/html/js_typed_interop_type_test.dart
index ba1f2da..a7195ab 100644
--- a/tests/lib/html/js_typed_interop_type_test.dart
+++ b/tests/lib/html/js_typed_interop_type_test.dart
@@ -26,7 +26,7 @@
@JS()
@anonymous
class C {
- final foo;
+ external get foo;
external factory C({foo});
}
@@ -34,7 +34,7 @@
@JS()
@anonymous
class D {
- final foo;
+ external get foo;
external factory D({foo});
}
diff --git a/tests/lib/js/js_annotation_static_test.dart b/tests/lib/js/js_annotation_static_test.dart
new file mode 100644
index 0000000..ef7dc40
--- /dev/null
+++ b/tests/lib/js/js_annotation_static_test.dart
@@ -0,0 +1,46 @@
+// Copyright (c) 2020, 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.
+
+// TODO(srujzs): Fix this test once web static error testing is supported.
+
+// Tests static errors for incorrect JS annotations.
+
+@JS()
+library js_annotation_static_test;
+
+import 'package:js/js.dart';
+
+class Foo {
+ // ^^^
+ // [web] TODO(srujzs): Test context once supported.
+ @JS()
+ external Foo(int bar);
+ // ^
+ // [web] TODO(srujzs): Add error once supported.
+ @JS()
+ external factory Foo.fooFactory();
+ // ^
+ // [web] TODO(srujzs): Add error once supported.
+ @JS()
+ external int get bar;
+ // ^^^
+ // [web] TODO(srujzs): Add error once supported.
+ @JS()
+ external set bar(int val);
+ // ^^^
+ // [web] TODO(srujzs): Add error once supported.
+ @JS()
+ external int baz();
+ // ^^^
+ // [web] TODO(srujzs): Add error once supported.
+ @JS()
+ external static int bazStatic();
+ // ^^^^^^^^^
+ // [web] TODO(srujzs): Add error once supported.
+}
+
+@JS()
+external int qux();
+
+main() {}
diff --git a/tests/standalone_2/standalone_2.status b/tests/standalone_2/standalone_2.status
index e9477e1..f99d678 100644
--- a/tests/standalone_2/standalone_2.status
+++ b/tests/standalone_2/standalone_2.status
@@ -60,6 +60,15 @@
io/wait_for_test: SkipByDesign # Uses mirrors.
verbose_gc_to_bmu_test: Skip # Attempts to spawn dart using Platform.executable
+[ $system == fuchsia ] # Fuchsia test runner doesn't support multi-tests yet.
+deny_listed_test: Skip
+io/dart_std_io_pipe_test: Skip
+io/platform_resolved_executable_test: Skip
+io/signals_exception_test: Skip
+io/socket_ipv6_test: Skip
+package/invalid_uri_test: Skip
+regress_29350_test: Skip
+
[ $builder_tag == swarming && $system == macos ]
io/*: Skip # Issue 30618
diff --git a/tools/VERSION b/tools/VERSION
index 7e59cc4..ab87528 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -1,39 +1 @@
-# This file is used by tools/utils.py to generate version strings.
-# The numbers are changed as follows:
-#
-# * New release cycle has begun (i.e. stable release was just made):
-# - increase MINOR by 1
-# - set "PATCH 0"
-# - set "PRERELEASE 0"
-# - set "PRERELEASE_PATCH 0"
-#
-# * Doing a push-to-trunk from bleeding_edge:
-# (The first push-to-trunk in the release cycle will set PRERELEASE to 0)
-# - increase PRERELEASE by 1
-# - set "PRERELEASE_PATCH 0"
-#
-# * Doing a cherry-pick to trunk:
-# - increase PRERELEASE_PATCH by 1
-#
-# * Making a stable release (i.e. new stable branch):
-# - set "PRERELEASE 0"
-# - set "PRERELEASE_PATCH 0"
-# The new stable release version will sort higher than the prereleases.
-#
-# * Making cherry-picks to stable channel
-# - increase PATCH by 1
-#
-# * Making a change to the ABI:
-# - increase ABI_VERSION by 1
-#
-# * Deprecating an old ABI version:
-# - increase OLDEST_SUPPORTED_ABI_VERSION to the version that is supported.
-#
-CHANNEL dev
-MAJOR 2
-MINOR 10
-PATCH 0
-PRERELEASE 4
-PRERELEASE_PATCH 0
-ABI_VERSION 39
-OLDEST_SUPPORTED_ABI_VERSION 39
+PRERELEASE_PATCH 0
\ No newline at end of file
diff --git a/tools/bots/test_matrix.json b/tools/bots/test_matrix.json
index 512d8a3..556782f 100644
--- a/tools/bots/test_matrix.json
+++ b/tools/bots/test_matrix.json
@@ -1339,24 +1339,6 @@
]
},
{
- "name": "co19 nnbd tests in weak mode with asserts",
- "arguments": [
- "-ndartkp-weak-asserts-${system}-${mode}-${arch}",
- "co19"
- ],
- "fileset": "vm-kernel",
- "shards": 3
- },
- {
- "name": "co19 nnbd tests in strong mode",
- "arguments": [
- "-ndartkp-strong-${system}-${mode}-${arch}",
- "co19"
- ],
- "fileset": "vm-kernel",
- "shards": 3
- },
- {
"name": "vm nnbd tests in weak mode with asserts",
"arguments": [
"-ndartkp-weak-asserts-${system}-${mode}-${arch}",
@@ -1368,7 +1350,7 @@
"vm"
],
"fileset": "vm-kernel",
- "shards": 3
+ "shards": 4
},
{
"name": "vm nnbd tests in strong mode",
@@ -1382,7 +1364,25 @@
"vm"
],
"fileset": "vm-kernel",
- "shards": 3
+ "shards": 4
+ },
+ {
+ "name": "co19 nnbd tests in strong mode",
+ "arguments": [
+ "-ndartkp-strong-${system}-${mode}-${arch}",
+ "co19"
+ ],
+ "fileset": "vm-kernel",
+ "shards": 4
+ },
+ {
+ "name": "co19 nnbd tests in weak mode with asserts",
+ "arguments": [
+ "-ndartkp-weak-asserts-${system}-${mode}-${arch}",
+ "co19"
+ ],
+ "fileset": "vm-kernel",
+ "shards": 4
}
]
},
@@ -2695,14 +2695,6 @@
"arguments": [
"api_docs"
]
- },
- {
- "name": "upload abi dills",
- "script": "tools/upload_abi_dills.sh",
- "arguments": [
- "tools/VERSION",
- "out/ReleaseX64"
- ]
}
]
},
diff --git a/tools/download_abi_dills.py b/tools/download_abi_dills.py
deleted file mode 100644
index 7ad544c..0000000
--- a/tools/download_abi_dills.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# Downloads dill files from CIPD for each supported ABI version.
-
-import os
-import subprocess
-import sys
-import utils
-
-
-def procWait(p):
- while p.returncode is None:
- p.communicate()
- p.poll()
- return p.returncode
-
-
-def findAbiVersion(version):
- cmd = ['cipd', 'instances', 'dart/abiversions/%d' % version]
- p = subprocess.Popen(
- cmd,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- shell=utils.IsWindows(),
- cwd=utils.DART_DIR)
- return procWait(p) == 0
-
-
-def main():
- abi_version = int(utils.GetAbiVersion())
- oldest_abi_version = int(utils.GetOldestSupportedAbiVersion())
- cmd = ['cipd', 'ensure', '-root', 'tools/abiversions', '-ensure-file', '-']
- ensure_file = ''
- for i in range(oldest_abi_version, abi_version + 1):
- if findAbiVersion(i):
- ensure_file += '@Subdir %d\ndart/abiversions/%d latest\n\n' % (i, i)
- if not ensure_file:
- return 0
- p = subprocess.Popen(
- cmd,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- shell=utils.IsWindows(),
- cwd=utils.DART_DIR)
- p.communicate(ensure_file)
- p.stdin.close()
- return procWait(p)
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/tools/generate_package_config.dart b/tools/generate_package_config.dart
index 169fbbc..0caf03b 100755
--- a/tools/generate_package_config.dart
+++ b/tools/generate_package_config.dart
@@ -34,9 +34,25 @@
packageDirectory('pkg/front_end/testcases/nonfunction_type_aliases/'),
];
+ var feAnalyzerSharedPackageDirs = [
+ packageDirectory(
+ 'pkg/_fe_analyzer_shared/test/flow_analysis/assigned_variables/'),
+ packageDirectory(
+ 'pkg/_fe_analyzer_shared/test/flow_analysis/definite_assignment/'),
+ packageDirectory(
+ 'pkg/_fe_analyzer_shared/test/flow_analysis/definite_unassignment/'),
+ packageDirectory('pkg/_fe_analyzer_shared/test/flow_analysis/nullability/'),
+ packageDirectory(
+ 'pkg/_fe_analyzer_shared/test/flow_analysis/reachability/'),
+ packageDirectory(
+ 'pkg/_fe_analyzer_shared/test/flow_analysis/type_promotion/'),
+ packageDirectory('pkg/_fe_analyzer_shared/test/inheritance/'),
+ ];
+
var packages = [
...makePackageConfigs(packageDirs),
- ...makeCfePackageConfigs(cfePackageDirs)
+ ...makeCfePackageConfigs(cfePackageDirs),
+ ...makeFeAnalyzerSharedPackageConfigs(feAnalyzerSharedPackageDirs)
];
packages.sort((a, b) => a["name"].compareTo(b["name"]));
@@ -107,6 +123,21 @@
}
}
+/// Generates package configurations for the special pseudo-packages used by
+/// the _fe_analyzer_shared id tests.
+Iterable<Map<String, String>> makeFeAnalyzerSharedPackageConfigs(
+ List<String> packageDirs) sync* {
+ for (var packageDir in packageDirs) {
+ yield {
+ 'name': '_fe_analyzer_shared_${p.basename(packageDir)}',
+ 'rootUri': p
+ .toUri(p.relative(packageDir, from: p.dirname(configFilePath)))
+ .toString(),
+ 'packageUri': '.nonexisting/',
+ };
+ }
+}
+
/// Generates a path to [relativePath] within the repo.
String packageDirectory(String relativePath) => p.join(repoRoot, relativePath);
diff --git a/tools/make_version.py b/tools/make_version.py
index f8356f8..1dc0dbe 100755
--- a/tools/make_version.py
+++ b/tools/make_version.py
@@ -108,14 +108,6 @@
version_time = 'Unknown timestamp'
version = version.replace('{{COMMIT_TIME}}', version_time.decode('utf-8'))
- abi_version = utils.GetAbiVersion(version_file)
- version = version.replace('{{ABI_VERSION}}', abi_version)
-
- oldest_supported_abi_version = utils.GetOldestSupportedAbiVersion(
- version_file)
- version = version.replace('{{OLDEST_SUPPORTED_ABI_VERSION}}',
- oldest_supported_abi_version)
-
snapshot_hash = MakeSnapshotHashString()
version = version.replace('{{SNAPSHOT_HASH}}', snapshot_hash)
diff --git a/tools/run_abi_tests.py b/tools/run_abi_tests.py
deleted file mode 100644
index 47566f6..0000000
--- a/tools/run_abi_tests.py
+++ /dev/null
@@ -1,215 +0,0 @@
-# Copyright (c) 2019, 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.
-
-# Runs tests with old ABI versions and check if the results differ from the
-# current results.
-
-import argparse
-import json
-import os
-import subprocess
-import sys
-import time
-import utils
-
-scriptDir = os.path.dirname(os.path.realpath(__file__))
-outDir = os.path.join(scriptDir, '..', 'out', 'ReleaseX64')
-abiDir = os.path.join(outDir, 'dart-sdk', 'lib', '_internal', 'abiversions')
-
-
-# Parse command line args to flags.
-def parseArgs():
- parser = argparse.ArgumentParser(
- 'Runs test.py on all supported ABI versions')
- parser.add_argument(
- '--output-directory',
- default=os.path.join(outDir, 'logs'),
- metavar='DIR',
- dest='logDir',
- help='Directory to output results.json and logs.json to.')
- parser.add_argument(
- '-n',
- metavar='NAME',
- dest='configuration_name',
- help='Name of the configuration to use in the results.')
- return parser.parse_args()
-
-
-# Info about a running test.
-class Test:
-
- def __init__(self, cmd, resultFile, logFile, version):
- self.cmd = cmd # The test command.
- self.resultFile = resultFile # The expected location of the result file.
- self.logFile = logFile # The expected location of the log file.
- self.version = version # The ABI version, or None.
-
-
-# Recursively make directories for the path.
-def makeDirs(path):
- try:
- os.makedirs(path)
- except OSError:
- pass
-
-
-# Build a Test object for the given version (or None).
-def buildTest(version):
- testDir = os.path.join(outDir,
- 'test%s' % ('' if version is None else str(version)))
- logDir = os.path.join(testDir, 'logs')
- makeDirs(logDir)
-
- vm_options = ['--enable-interpreter']
- if version is not None:
- vm_options += ['--use-abi-version=%d' % version]
- cmd = [
- 'python',
- os.path.join(scriptDir, 'test.py'),
- '--compiler=dartkb',
- '--mode=release',
- '--write-results',
- '--write-logs',
- '--output_directory=%s' % logDir,
- '--vm-options=%s' % ' '.join(vm_options),
- 'lib_2',
- ]
-
- resultFile = os.path.join(logDir, 'results.json')
- logFile = os.path.join(logDir, 'logs.json')
- return Test(cmd, resultFile, logFile, version)
-
-
-# Returns whether the dill files exist for an ABI version.
-def abiVersionExists(version):
- return os.path.isdir(os.path.join(abiDir, str(version)))
-
-
-# Build tests for every supported version, and return a list of Test objects.
-def buildAllTests():
- abi_version = int(utils.GetAbiVersion())
- oldest_abi_version = int(utils.GetOldestSupportedAbiVersion())
- tests = [buildTest(None)]
- for version in xrange(oldest_abi_version, abi_version + 1):
- if abiVersionExists(version):
- tests.append(buildTest(version))
- return tests
-
-
-# Run all tests, one by one, and wait for them all to complete.
-def runAllTests(tests):
- for test in tests:
- print('\n\n\n=== Running tests %s ===' % (
- ('for ABI version %d' % test.version)
- if test.version is not None else ('without an ABI version')))
- print(subprocess.list2cmdline(test.cmd) + '\n\n')
- proc = subprocess.Popen(test.cmd)
- while proc.returncode is None:
- time.sleep(1)
- proc.communicate()
- proc.poll()
-
-
-# Read a test result file or log file and convert JSON lines to a dictionary of
-# JSON records indexed by name. Assumes result and log files both use name key.
-def readTestFile(fileName):
- with open(fileName, 'r') as f:
- return {r['name']: r for r in [json.loads(line) for line in f]}
-
-
-# Read the test result or log files for every version and return a dict like:
-# {name: {version: resultJson, ...}, ...}
-def readAllTestFiles(tests, nameGetter):
- allRecords = {}
- for test in tests:
- records = readTestFile(nameGetter(test))
- for name, result in records.items():
- if name not in allRecords:
- allRecords[name] = {}
- allRecords[name][test.version] = result
- return allRecords
-
-
-# Pick any element of the dictionary, favoring the None key if it exists.
-def pickOne(d):
- if None in d:
- return d[None]
- for v in d.values():
- return v
- return None
-
-
-# Diff the results of a test for each version and construct a new test result
-# that reports whether the test results match for each version.
-def diffResults(results, configuration_name):
- outResult = pickOne(results)
- exp = results[None]['result'] if None in results else None
- outResult['configuration'] = configuration_name
- outResult['expected'] = exp
- outResult['result'] = exp
- outResult['matches'] = True
- diffs = []
- for version, result in results.items():
- if version is not None:
- act = result['result']
- if exp != act:
- diffs.append(version)
- outResult[
- 'result'] = act # May be overwritten by other versions.
- outResult['matches'] = False
- return outResult, diffs
-
-
-# Create a log entry for a test that has diffs. Concatenate all the log records
-# and include which tests failed.
-def makeLog(diffs, results, logRecords, configuration_name):
- result = pickOne(results)
- logs = ["%s: %s" % (str(v), l['log']) for v, l in logRecords.items()]
- log = ('This test fails if there is a difference in the test results\n'
- 'between ABI versions. The expected result is the result on the\n'
- 'current ABI: %s\n'
- 'These ABI versions reported a different result: %s\n\n'
- 'These are the logs of the test runs on different ABI versions.\n'
- 'There are no logs for versions where the test passed.\n\n%s' %
- (result['result'], repr(diffs), '\n\n\n'.join(logs)))
- return {
- 'name': result['name'],
- 'configuration': configuration_name,
- 'result': result['result'],
- 'log': log,
- }
-
-
-# Diff the results of all the tests and create the merged result and log files.
-def diffAllResults(tests, flags):
- allResults = readAllTestFiles(tests, lambda test: test.resultFile)
- allLogs = readAllTestFiles(tests, lambda test: test.logFile)
- makeDirs(flags.logDir)
- resultFileName = os.path.join(flags.logDir, 'results.json')
- logFileName = os.path.join(flags.logDir, 'logs.json')
- with open(resultFileName, 'w') as resultFile:
- with open(logFileName, 'w') as logFile:
- for name, results in allResults.items():
- outResult, diffs = diffResults(results,
- flags.configuration_name)
- resultFile.write(json.dumps(outResult) + '\n')
- if diffs:
- logRecords = allLogs.get(name, {})
- logFile.write(
- json.dumps(
- makeLog(diffs, results, logRecords, flags.
- configuration_name)) + '\n')
- print('Log files emitted to %s and %s' % (resultFileName, logFileName))
-
-
-def main():
- flags = parseArgs()
- tests = buildAllTests()
- runAllTests(tests)
- diffAllResults(tests, flags)
- return 0
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/tools/upload_abi_dills.sh b/tools/upload_abi_dills.sh
deleted file mode 100755
index 28d3627..0000000
--- a/tools/upload_abi_dills.sh
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env bash
-
-# Copyright (c) 2019, 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.
-
-# Uploads the following dill files to CIPD, indexed by the current ABI version:
-# $build_dir/vm_platform_strong.dill
-# $build_dir/gen/kernel_service.dill
-# $build_dir/gen_kernel_bytecode.dill
-# This script is a no-op unless $BUILDBOT_BUILDERNAME is "dart-sdk-linux-be".
-# It's also a no-op if dill files were already uploaded today.
-#
-# If the ABI was modified, the ABI_VERSION in tools/VERSIONS should be manually
-# incremented accordingly.
-set -e
-set -x
-
-if [ -z "$2" ]; then
- echo "Usage: upload_abi_dills.sh version_file build_dir"
- exit 1
-fi
-
-if [ "$BUILDBOT_BUILDERNAME" != "dart-sdk-linux-be" ]; then
- echo "This script only works on the dart-sdk-linux-be buildbot"
- exit 0
-fi
-
-abi_version=$(sed -n "s/^ABI_VERSION \([0-9]*\)$/\1/p" "$1")
-git_revision=$(git rev-parse HEAD)
-current_date=$(date +%F)
-search_results=$(cipd search \
- "dart/abiversions/$abi_version" \
- -tag "date:$current_date" | grep "Instances:" || echo "")
-
-if [ ! -z "$search_results" ]; then
- exit 0
-fi
-
-sdk_dir=$(pwd)
-tmpdir=$(mktemp -d)
-chmod 755 $tmpdir
-cleanup() {
- rm -rf "$tmpdir"
-}
-trap cleanup EXIT HUP INT QUIT TERM PIPE
-pushd "$tmpdir"
-
-mkdir abiversions
-cp "$sdk_dir/$2/vm_platform_strong.dill" "abiversions/vm_platform_strong.dill"
-cp "$sdk_dir/$2/gen/kernel_service.dill" "abiversions/kernel_service.dill"
-cp "$sdk_dir/$2/gen_kernel_bytecode.dill" "abiversions/gen_kernel_bytecode.dill"
-
-cipd create \
- -name dart/abiversions/$abi_version \
- -in abiversions \
- -install-mode copy \
- -tag version:$abi_version \
- -tag date:$current_date \
- -tag git_revision:$git_revision \
- -ref latest \
- -ref version_$abi_version
-
-popd
diff --git a/tools/utils.py b/tools/utils.py
index 23c8812..cbd1759 100644
--- a/tools/utils.py
+++ b/tools/utils.py
@@ -114,15 +114,13 @@
class Version(object):
def __init__(self, channel, major, minor, patch, prerelease,
- prerelease_patch, abi_version, oldest_supported_abi_version):
+ prerelease_patch):
self.channel = channel
self.major = major
self.minor = minor
self.patch = patch
self.prerelease = prerelease
self.prerelease_patch = prerelease_patch
- self.abi_version = abi_version
- self.oldest_supported_abi_version = oldest_supported_abi_version
# Try to guess the host operating system.
@@ -410,16 +408,6 @@
return os.environ.get(key, '')
-def GetAbiVersion(version_file=None):
- version = ReadVersionFile(version_file)
- return version.abi_version
-
-
-def GetOldestSupportedAbiVersion(version_file=None):
- version = ReadVersionFile(version_file)
- return version.oldest_supported_abi_version
-
-
def ReadVersionFile(version_file=None):
def match_against(pattern, file_content):
@@ -445,15 +433,10 @@
patch = match_against('^PATCH (\d+)$', content)
prerelease = match_against('^PRERELEASE (\d+)$', content)
prerelease_patch = match_against('^PRERELEASE_PATCH (\d+)$', content)
- abi_version = match_against('^ABI_VERSION (\d+)$', content)
- oldest_supported_abi_version = match_against(
- '^OLDEST_SUPPORTED_ABI_VERSION (\d+)$', content)
- if (channel and major and minor and prerelease and prerelease_patch and
- abi_version and oldest_supported_abi_version):
+ if (channel and major and minor and prerelease and prerelease_patch):
return Version(channel, major, minor, patch, prerelease,
- prerelease_patch, abi_version,
- oldest_supported_abi_version)
+ prerelease_patch)
print('Warning: VERSION file ({}) has wrong format'.format(version_file))
return None
diff --git a/utils/compiler/create_snapshot_entry.dart b/utils/compiler/create_snapshot_entry.dart
index 633667c..d915d4d 100644
--- a/utils/compiler/create_snapshot_entry.dart
+++ b/utils/compiler/create_snapshot_entry.dart
@@ -10,10 +10,9 @@
import 'dart:async';
Future<String> getVersion(var rootPath) {
- var suffix = Platform.operatingSystem == 'windows' ? '.exe' : '';
var printVersionScript = rootPath.resolve("tools/make_version.py");
return Process.run(
- "python$suffix", [printVersionScript.toFilePath(), "--quiet"])
+ "python", [printVersionScript.toFilePath(), "--quiet"], runInShell:true)
.then((result) {
if (result.exitCode != 0) {
throw "Could not generate version";